text stringlengths 8 4.13M |
|---|
use core::marker::PhantomData;
use alloc::vec::Vec;
use array2d::Array2D;
use necsim_core::{
cogs::{Backup, Habitat, RngCore},
landscape::Location,
};
use crate::cogs::dispersal_sampler::in_memory::InMemoryDispersalSampler;
mod dispersal;
use crate::alias::AliasMethodSampler;
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct InMemoryAliasDispersalSampler<H: Habitat, G: RngCore> {
alias_dispersal: Array2D<Option<AliasMethodSampler<usize>>>,
marker: PhantomData<(H, G)>,
}
#[contract_trait]
impl<H: Habitat, G: RngCore> InMemoryDispersalSampler<H, G>
for InMemoryAliasDispersalSampler<H, G>
{
/// Creates a new `InMemoryAliasDispersalSampler` from the
/// `dispersal` map and extent of the habitat map.
fn unchecked_new(dispersal: &Array2D<f64>, habitat: &H) -> Self {
let habitat_extent = habitat.get_extent();
let mut event_weights: Vec<(usize, f64)> = Vec::with_capacity(dispersal.row_len());
let alias_dispersal = Array2D::from_iter_row_major(
dispersal.rows_iter().map(|row| {
event_weights.clear();
for (col_index, dispersal_probability) in row.enumerate() {
#[allow(clippy::cast_possible_truncation)]
let location = Location::new(
(col_index % (habitat_extent.width() as usize)) as u32 + habitat_extent.x(),
(col_index / (habitat_extent.width() as usize)) as u32 + habitat_extent.y(),
);
// Multiply all dispersal probabilities by the habitat of their target
let weight = dispersal_probability
* f64::from(habitat.get_habitat_at_location(&location));
if weight > 0.0_f64 {
event_weights.push((col_index, weight));
}
}
if event_weights.is_empty() {
None
} else {
Some(AliasMethodSampler::new(&event_weights))
}
}),
habitat_extent.height() as usize,
habitat_extent.width() as usize,
)
.unwrap(); // infallible by PRE
Self {
alias_dispersal,
marker: PhantomData::<(H, G)>,
}
}
}
#[contract_trait]
impl<H: Habitat, G: RngCore> Backup for InMemoryAliasDispersalSampler<H, G> {
unsafe fn backup_unchecked(&self) -> Self {
Self {
alias_dispersal: self.alias_dispersal.clone(),
marker: PhantomData::<(H, G)>,
}
}
}
|
use std::time::Instant;
fn main() {
let start = Instant::now();
let mut count = 0;
loop {
count += 1;
if count == 1000000 {
break;
}
}
let duration = start.elapsed();
println!("{:?}", duration);
}
|
#[doc = "Reader of register FLEVEL"]
pub type R = crate::R<u32, super::FLEVEL>;
#[doc = "Reader of field `RX3`"]
pub type RX3_R = crate::R<u8, u8>;
#[doc = "Reader of field `TX3`"]
pub type TX3_R = crate::R<u8, u8>;
#[doc = "Reader of field `RX2`"]
pub type RX2_R = crate::R<u8, u8>;
#[doc = "Reader of field `TX2`"]
pub type TX2_R = crate::R<u8, u8>;
#[doc = "Reader of field `RX1`"]
pub type RX1_R = crate::R<u8, u8>;
#[doc = "Reader of field `TX1`"]
pub type TX1_R = crate::R<u8, u8>;
#[doc = "Reader of field `RX0`"]
pub type RX0_R = crate::R<u8, u8>;
#[doc = "Reader of field `TX0`"]
pub type TX0_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 28:31"]
#[inline(always)]
pub fn rx3(&self) -> RX3_R {
RX3_R::new(((self.bits >> 28) & 0x0f) as u8)
}
#[doc = "Bits 24:27"]
#[inline(always)]
pub fn tx3(&self) -> TX3_R {
TX3_R::new(((self.bits >> 24) & 0x0f) as u8)
}
#[doc = "Bits 20:23"]
#[inline(always)]
pub fn rx2(&self) -> RX2_R {
RX2_R::new(((self.bits >> 20) & 0x0f) as u8)
}
#[doc = "Bits 16:19"]
#[inline(always)]
pub fn tx2(&self) -> TX2_R {
TX2_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 12:15"]
#[inline(always)]
pub fn rx1(&self) -> RX1_R {
RX1_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 8:11"]
#[inline(always)]
pub fn tx1(&self) -> TX1_R {
TX1_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 4:7"]
#[inline(always)]
pub fn rx0(&self) -> RX0_R {
RX0_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 0:3"]
#[inline(always)]
pub fn tx0(&self) -> TX0_R {
TX0_R::new((self.bits & 0x0f) as u8)
}
}
|
#[doc = "Register `CCIPR2` reader"]
pub type R = crate::R<CCIPR2_SPEC>;
#[doc = "Register `CCIPR2` writer"]
pub type W = crate::W<CCIPR2_SPEC>;
#[doc = "Field `I2C4SEL` reader - I2C4 clock source selection"]
pub type I2C4SEL_R = crate::FieldReader<I2C4SEL_A>;
#[doc = "I2C4 clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum I2C4SEL_A {
#[doc = "0: PCLK clock selected as I2C clock"]
Pclk = 0,
#[doc = "1: System clock (SYSCLK) selected as I2C clock"]
System = 1,
#[doc = "2: HSI16 clock selected as I2C clock"]
Hsi16 = 2,
}
impl From<I2C4SEL_A> for u8 {
#[inline(always)]
fn from(variant: I2C4SEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for I2C4SEL_A {
type Ux = u8;
}
impl I2C4SEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<I2C4SEL_A> {
match self.bits {
0 => Some(I2C4SEL_A::Pclk),
1 => Some(I2C4SEL_A::System),
2 => Some(I2C4SEL_A::Hsi16),
_ => None,
}
}
#[doc = "PCLK clock selected as I2C clock"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
*self == I2C4SEL_A::Pclk
}
#[doc = "System clock (SYSCLK) selected as I2C clock"]
#[inline(always)]
pub fn is_system(&self) -> bool {
*self == I2C4SEL_A::System
}
#[doc = "HSI16 clock selected as I2C clock"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == I2C4SEL_A::Hsi16
}
}
#[doc = "Field `I2C4SEL` writer - I2C4 clock source selection"]
pub type I2C4SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, I2C4SEL_A>;
impl<'a, REG, const O: u8> I2C4SEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "PCLK clock selected as I2C clock"]
#[inline(always)]
pub fn pclk(self) -> &'a mut crate::W<REG> {
self.variant(I2C4SEL_A::Pclk)
}
#[doc = "System clock (SYSCLK) selected as I2C clock"]
#[inline(always)]
pub fn system(self) -> &'a mut crate::W<REG> {
self.variant(I2C4SEL_A::System)
}
#[doc = "HSI16 clock selected as I2C clock"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(I2C4SEL_A::Hsi16)
}
}
#[doc = "Field `QSPISEL` reader - Octospi clock source selection"]
pub type QSPISEL_R = crate::FieldReader<QSPISEL_A>;
#[doc = "Octospi clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum QSPISEL_A {
#[doc = "0: System clock selected as QUADSPI kernel clock"]
System = 0,
#[doc = "1: HSI16 clock selected as QUADSPI kernel clock"]
Hsi16 = 1,
#[doc = "2: PLL 'Q' clock selected as QUADSPI kernel clock"]
Pllq = 2,
}
impl From<QSPISEL_A> for u8 {
#[inline(always)]
fn from(variant: QSPISEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for QSPISEL_A {
type Ux = u8;
}
impl QSPISEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<QSPISEL_A> {
match self.bits {
0 => Some(QSPISEL_A::System),
1 => Some(QSPISEL_A::Hsi16),
2 => Some(QSPISEL_A::Pllq),
_ => None,
}
}
#[doc = "System clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn is_system(&self) -> bool {
*self == QSPISEL_A::System
}
#[doc = "HSI16 clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn is_hsi16(&self) -> bool {
*self == QSPISEL_A::Hsi16
}
#[doc = "PLL 'Q' clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn is_pllq(&self) -> bool {
*self == QSPISEL_A::Pllq
}
}
#[doc = "Field `QSPISEL` writer - Octospi clock source selection"]
pub type QSPISEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, QSPISEL_A>;
impl<'a, REG, const O: u8> QSPISEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "System clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn system(self) -> &'a mut crate::W<REG> {
self.variant(QSPISEL_A::System)
}
#[doc = "HSI16 clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn hsi16(self) -> &'a mut crate::W<REG> {
self.variant(QSPISEL_A::Hsi16)
}
#[doc = "PLL 'Q' clock selected as QUADSPI kernel clock"]
#[inline(always)]
pub fn pllq(self) -> &'a mut crate::W<REG> {
self.variant(QSPISEL_A::Pllq)
}
}
impl R {
#[doc = "Bits 0:1 - I2C4 clock source selection"]
#[inline(always)]
pub fn i2c4sel(&self) -> I2C4SEL_R {
I2C4SEL_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 20:21 - Octospi clock source selection"]
#[inline(always)]
pub fn qspisel(&self) -> QSPISEL_R {
QSPISEL_R::new(((self.bits >> 20) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - I2C4 clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c4sel(&mut self) -> I2C4SEL_W<CCIPR2_SPEC, 0> {
I2C4SEL_W::new(self)
}
#[doc = "Bits 20:21 - Octospi clock source selection"]
#[inline(always)]
#[must_use]
pub fn qspisel(&mut self) -> QSPISEL_W<CCIPR2_SPEC, 20> {
QSPISEL_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Peripherals independent clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccipr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCIPR2_SPEC;
impl crate::RegisterSpec for CCIPR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccipr2::R`](R) reader structure"]
impl crate::Readable for CCIPR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccipr2::W`](W) writer structure"]
impl crate::Writable for CCIPR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCIPR2 to value 0"]
impl crate::Resettable for CCIPR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
fn main() {
proconio::input! {
n: usize,
s: String,
q: usize,
tab: [(usize, i32, i32); q],
}
let mut cs: Vec<char> = s.chars().collect();
let mut ai = 0;
let mut bi = 0;
let mut sei = true;
for i in 0..q {
let t = tab[i];
if t.0 == 1 {
if sei {
ai = t.1-1;
bi = t.2-1;
}else{
ai = t.1-1 - n as i32;
bi = t.2-1 - n as i32;
if ai < 0 {
ai = ai + 2 * n as i32;
}
if bi < 0 {
bi = bi + 2 * n as i32;
}
}
let tmp = cs[ai as usize];
cs[ai as usize] = cs[bi as usize];
cs[bi as usize] = tmp;
}else{
sei = !sei;
}
}
if !sei {
let mut later = cs.split_off(n);
later.append(&mut cs);
cs = later;
}
let pb: Vec<String> = cs.iter().map(|x| x.to_string()).collect();
println!("{}", pb.join(""));
}
|
//! RTE PMD Driver Registration Interface
//!
//! This file manages the list of device drivers.
//!
use std::ffi::CStr;
use std::mem;
use std::os::raw::{c_char, c_void};
use anyhow::Result;
use errors::AsResult;
use ffi::{self, rte_dev_event_type::*};
use utils::AsCString;
/// The device event type.
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)]
pub enum Event {
/// device being added
Add = RTE_DEV_EVENT_ADD,
/// device being removed
Remove = RTE_DEV_EVENT_REMOVE,
/// max value of this enum
Max = RTE_DEV_EVENT_MAX,
}
pub type RawDevice = ffi::rte_device;
pub type RawDevicePtr = *mut ffi::rte_device;
#[repr(transparent)]
#[derive(Debug)]
pub struct Device(RawDevicePtr);
impl From<RawDevicePtr> for Device {
fn from(p: RawDevicePtr) -> Self {
Device(p)
}
}
impl Device {
/// Query status of a device.
pub fn is_probed(&self) -> bool {
unsafe { ffi::rte_dev_is_probed(self.0) != 0 }
}
/// Remove one device.
///
/// In multi-process, it will request other processes to remove the same device.
/// A failure, in any process, will rollback the action
pub fn remove(&self) -> Result<()> {
unsafe { ffi::rte_dev_remove(self.0) }.as_result().map(|_| ())
}
}
/// Hotplug add a given device to a specific bus.
///
/// In multi-process, it will request other processes to add the same device.
/// A failure, in any process, will rollback the action
pub fn hotplug_add(busname: &str, devname: &str, drvargs: &str) -> Result<()> {
let busname = busname.as_cstring();
let devname = devname.as_cstring();
let drvargs = drvargs.as_cstring();
unsafe { ffi::rte_eal_hotplug_add(busname.as_ptr(), devname.as_ptr(), drvargs.as_ptr()) }
.as_result()
.map(|_| ())
}
/// Hotplug remove a given device from a specific bus.
///
/// In multi-process, it will request other processes to remove the same device.
/// A failure, in any process, will rollback the action
pub fn hotplug_remove(busname: &str, devname: &str) -> Result<()> {
let busname = busname.as_cstring();
let devname = devname.as_cstring();
unsafe { ffi::rte_eal_hotplug_remove(busname.as_ptr(), devname.as_ptr()) }
.as_result()
.map(|_| ())
}
pub type EventCallback<T> = fn(devname: &str, Event, Option<T>);
struct EventContext<T> {
callback: EventCallback<T>,
arg: Option<T>,
}
unsafe extern "C" fn event_stub<T>(devname: *const c_char, event: ffi::rte_dev_event_type::Type, arg: *mut c_void) {
let devname = CStr::from_ptr(devname);
let ctxt = Box::from_raw(arg as *mut EventContext<T>);
(ctxt.callback)(devname.to_str().unwrap(), mem::transmute(event), ctxt.arg)
}
/// It registers the callback for the specific device.
/// Multiple callbacks cal be registered at the same time.
pub fn event_callback_register<T>(devname: &str, callback: EventCallback<T>, arg: Option<T>) -> Result<()> {
let devname = devname.as_cstring();
let ctxt = Box::into_raw(Box::new(EventContext::<T> { callback, arg }));
unsafe { ffi::rte_dev_event_callback_register(devname.as_ptr(), Some(event_stub::<T>), ctxt as *mut _) }
.as_result()
.map(|_| ())
}
|
use crate::component::type_to_inject::TypeToInject;
use proc_macro2::TokenStream as TokenStream2;
use quote::ToTokens;
use syn::spanned::Spanned;
use syn::{Error, Ident, PathArguments};
pub(crate) trait Injector {
fn generate_inject_code(&self, to_inject: &TypeToInject, container: &Ident) -> Option<TokenStream2>;
}
pub(crate) struct WrcInjector;
impl Injector for WrcInjector {
fn generate_inject_code(&self, to_inject: &TypeToInject, container: &Ident) -> Option<TokenStream2> {
#[cfg(feature = "async")]
const RC_FULL_TYPE: &str = "std :: sync :: Arc <";
#[cfg(not(feature = "async"))]
const RC_FULL_TYPE: &str = "std :: rc :: Rc <";
#[cfg(feature = "async")]
const RC_SHORT_TYPE: &str = "Arc <";
#[cfg(not(feature = "async"))]
const RC_SHORT_TYPE: &str = "Rc <";
let referenced_type_opt = if to_inject.type_name.starts_with("inexor_rgf_core_di :: Wrc <") || to_inject.type_name.starts_with(RC_FULL_TYPE) {
Some(get_type_arg(&to_inject.type_path.segments[2].arguments))
} else if to_inject.type_name.starts_with("Wrc <") || to_inject.type_name.starts_with(RC_SHORT_TYPE) {
Some(get_type_arg(&to_inject.type_path.segments[0].arguments))
} else {
None
};
referenced_type_opt.map(|ref_type| {
quote::quote! {
inexor_rgf_core_di::Provider::<#ref_type>::get(#container)
}
})
}
}
pub(crate) struct BoxInjector;
impl Injector for BoxInjector {
fn generate_inject_code(&self, to_inject: &TypeToInject, container: &Ident) -> Option<TokenStream2> {
if to_inject.type_name.starts_with("Box <") {
let referenced_type = get_type_arg(&to_inject.type_path.segments[0].arguments);
return Some(quote::quote! {
Box::new(inexor_rgf_core_di::Provider::<#referenced_type>::create(#container))
});
}
None
}
}
pub(crate) struct DeferredInjector;
impl Injector for DeferredInjector {
fn generate_inject_code(&self, to_inject: &TypeToInject, _container: &Ident) -> Option<TokenStream2> {
let referenced_type_opt = if to_inject.type_name.starts_with("inexor_rgf_core_di :: Deferred <") {
Some(get_type_arg(&to_inject.type_path.segments[1].arguments))
} else if to_inject.type_name.starts_with("Deferred <") {
Some(get_type_arg(&to_inject.type_path.segments[0].arguments))
} else {
None
};
referenced_type_opt.map(|ref_type| {
quote::quote! {
inexor_rgf_core_di::Deferred::<#ref_type>::new()
}
})
}
}
pub(crate) struct ConfigInjector;
impl Injector for ConfigInjector {
fn generate_inject_code(&self, to_inject: &TypeToInject, container: &Ident) -> Option<TokenStream2> {
if to_inject.type_name == "Config".to_string() || to_inject.type_name == "config :: Config".to_string() {
return Some(quote::quote! { #container.config.clone() });
}
None
}
}
pub(crate) struct PropInjector;
impl Injector for PropInjector {
fn generate_inject_code(&self, to_inject: &TypeToInject, container: &Ident) -> Option<TokenStream2> {
let (prop_name_opt, default_value_code) = if to_inject.prop_attr.is_some() {
let prop_attr = to_inject.prop_attr.clone().unwrap();
let prop_name_opt = prop_attr.name.clone().or(to_inject.arg_name.clone().map(|name_ts| name_ts.to_string()));
let default_value_code = prop_attr
.default_value
.clone()
.map(|default_value| quote::quote! { .or_else(|| Some(#default_value)) })
.unwrap_or(quote::quote! {});
(prop_name_opt, default_value_code)
} else {
(to_inject.arg_name.clone().map(|name_ts| name_ts.to_string()), quote::quote! {})
};
let base_types_extracted = prop_name_opt.and_then(|prop_name_tokens| {
let prop_name = prop_name_tokens.to_string();
let (type_path, opt_extractor) = if to_inject.type_name.starts_with("Option <") {
(get_type_arg(&to_inject.type_path.segments[0].arguments), quote::quote! {})
} else {
(
to_inject.type_path.to_token_stream(),
quote::quote! { .expect(format!("Property \"{}\" not found", #prop_name).as_str()) },
)
};
let type_name = type_path.to_string();
let mut extractors: Vec<Box<dyn PropExtractor>> = Vec::new();
extractors.push(Box::new(SafeCastPropExtractor));
extractors.push(Box::new(UnsafeCastPropExtractor));
extractors.push(Box::new(AsCastPropExtractor));
extractors.iter().find_map(|extractor| {
extractor.generate_extract_method(type_name.clone()).map(|extract_method| {
let convert_code = extractor.generate_convert_code(type_path.clone(), type_name.clone(), prop_name.to_string(), quote::quote! { value });
quote::quote! {
#container.config.#extract_method(#prop_name)
.map(|value| #convert_code)
.ok()
#default_value_code
#opt_extractor
}
})
})
});
base_types_extracted.or_else(|| {
if to_inject.prop_attr.is_some() {
let type_name = to_inject.type_name.clone();
let type_path = to_inject.type_path.clone();
Some(quote::quote! {
#container.config.clone().try_into::<#type_path>()
.expect(format!("Can't parse config as '{}'", #type_name).as_str())
})
} else {
None
}
})
}
}
trait PropExtractor {
fn generate_extract_method(&self, type_name: String) -> Option<TokenStream2>;
fn generate_convert_code(&self, _type_path: TokenStream2, _type_name: String, _prop_name: String, extract_code: TokenStream2) -> TokenStream2 {
extract_code
}
}
struct SafeCastPropExtractor;
impl PropExtractor for SafeCastPropExtractor {
fn generate_extract_method(&self, type_name: String) -> Option<TokenStream2> {
match type_name.as_str() {
"i128" | "u128" => Some(quote::quote! { get_int }),
_ => None,
}
}
fn generate_convert_code(&self, type_path: TokenStream2, _type_name: String, _prop_name: String, value: TokenStream2) -> TokenStream2 {
quote::quote! { #type_path::from(#value) }
}
}
struct UnsafeCastPropExtractor;
impl PropExtractor for UnsafeCastPropExtractor {
fn generate_extract_method(&self, type_name: String) -> Option<TokenStream2> {
match type_name.as_str() {
"i8" | "i16" | "i32" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" => Some(quote::quote! { get_int }),
_ => None,
}
}
fn generate_convert_code(&self, type_path: TokenStream2, type_name: String, prop_name: String, value: TokenStream2) -> TokenStream2 {
quote::quote! {
<#type_path as std::convert::TryFrom<i64>>::try_from(#value)
.expect(format!("Can't parse prop '{}' as '{}'", #prop_name, #type_name).as_str())
}
}
}
struct AsCastPropExtractor;
impl PropExtractor for AsCastPropExtractor {
fn generate_extract_method(&self, type_name: String) -> Option<TokenStream2> {
match type_name.as_str() {
"i64" => Some(quote::quote! { get_int }),
"f64" | "f32" => Some(quote::quote! { get_float }),
"String" => Some(quote::quote! { get_str }),
"bool" => Some(quote::quote! { get_bool }),
_ => None,
}
}
fn generate_convert_code(&self, type_path: TokenStream2, _type_name: String, _prop_name: String, value: TokenStream2) -> TokenStream2 {
quote::quote! {
#value as #type_path
}
}
}
fn get_type_arg(arguments: &PathArguments) -> TokenStream2 {
if let PathArguments::AngleBracketed(ab) = arguments {
ab.args.to_token_stream()
} else {
Error::new(arguments.span(), "Unsupported type argument").to_compile_error()
}
}
|
//! The `vote_stage` votes on the `last_id` of the bank at a regular cadence
use bank::Bank;
use bincode::serialize;
use budget_transaction::BudgetTransaction;
use cluster_info::ClusterInfo;
use counter::Counter;
use hash::Hash;
use influx_db_client as influxdb;
use log::Level;
use metrics;
use packet::SharedBlob;
use result::Result;
use signature::Keypair;
use solana_program_interface::pubkey::Pubkey;
use std::result;
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, RwLock};
use streamer::BlobSender;
use timing;
use transaction::Transaction;
pub const VOTE_TIMEOUT_MS: u64 = 1000;
#[derive(Debug, PartialEq, Eq)]
enum VoteError {
NoValidLastIdsToVoteOn,
}
pub fn create_new_signed_vote_blob(
last_id: &Hash,
keypair: &Keypair,
cluster_info: &Arc<RwLock<ClusterInfo>>,
) -> Result<SharedBlob> {
let shared_blob = SharedBlob::default();
let (vote, addr) = {
let mut wcluster_info = cluster_info.write().unwrap();
//TODO: doesn't seem like there is a synchronous call to get height and id
debug!("voting on {:?}", &last_id.as_ref()[..8]);
wcluster_info.new_vote(*last_id)
}?;
let tx = Transaction::budget_new_vote(&keypair, vote, *last_id, 0);
{
let mut blob = shared_blob.write().unwrap();
let bytes = serialize(&tx)?;
let len = bytes.len();
blob.data[..len].copy_from_slice(&bytes);
blob.meta.set_addr(&addr);
blob.meta.size = len;
}
Ok(shared_blob)
}
fn get_last_id_to_vote_on(
id: &Pubkey,
ids: &[Hash],
bank: &Arc<Bank>,
now: u64,
last_vote: &mut u64,
last_valid_validator_timestamp: &mut u64,
) -> result::Result<(Hash, u64), VoteError> {
let mut valid_ids = bank.count_valid_ids(&ids);
let super_majority_index = (2 * ids.len()) / 3;
//TODO(anatoly): this isn't stake based voting
debug!(
"{}: valid_ids {}/{} {}",
id,
valid_ids.len(),
ids.len(),
super_majority_index,
);
metrics::submit(
influxdb::Point::new("vote_stage-peer_count")
.add_field("total_peers", influxdb::Value::Integer(ids.len() as i64))
.add_field(
"valid_peers",
influxdb::Value::Integer(valid_ids.len() as i64),
).to_owned(),
);
if valid_ids.len() > super_majority_index {
*last_vote = now;
// Sort by timestamp
valid_ids.sort_by(|a, b| a.1.cmp(&b.1));
let last_id = ids[valid_ids[super_majority_index].0];
return Ok((last_id, valid_ids[super_majority_index].1));
}
if *last_valid_validator_timestamp != 0 {
metrics::submit(
influxdb::Point::new(&"leader-finality")
.add_field(
"duration_ms",
influxdb::Value::Integer((now - *last_valid_validator_timestamp) as i64),
).to_owned(),
);
}
Err(VoteError::NoValidLastIdsToVoteOn)
}
pub fn send_leader_vote(
id: &Pubkey,
keypair: &Keypair,
bank: &Arc<Bank>,
cluster_info: &Arc<RwLock<ClusterInfo>>,
vote_blob_sender: &BlobSender,
last_vote: &mut u64,
last_valid_validator_timestamp: &mut u64,
) -> Result<()> {
let now = timing::timestamp();
if now - *last_vote > VOTE_TIMEOUT_MS {
let ids: Vec<_> = cluster_info.read().unwrap().valid_last_ids();
if let Ok((last_id, super_majority_timestamp)) = get_last_id_to_vote_on(
id,
&ids,
bank,
now,
last_vote,
last_valid_validator_timestamp,
) {
if let Ok(shared_blob) = create_new_signed_vote_blob(&last_id, keypair, cluster_info) {
vote_blob_sender.send(vec![shared_blob])?;
let finality_ms = now - super_majority_timestamp;
*last_valid_validator_timestamp = super_majority_timestamp;
debug!("{} leader_sent_vote finality: {} ms", id, finality_ms);
inc_new_counter_info!("vote_stage-leader_sent_vote", 1);
bank.set_finality((now - *last_valid_validator_timestamp) as usize);
metrics::submit(
influxdb::Point::new(&"leader-finality")
.add_field("duration_ms", influxdb::Value::Integer(finality_ms as i64))
.to_owned(),
);
}
}
}
Ok(())
}
pub fn send_validator_vote(
bank: &Arc<Bank>,
keypair: &Arc<Keypair>,
cluster_info: &Arc<RwLock<ClusterInfo>>,
vote_blob_sender: &BlobSender,
) -> Result<()> {
let last_id = bank.last_id();
if let Ok(shared_blob) = create_new_signed_vote_blob(&last_id, keypair, cluster_info) {
inc_new_counter_info!("replicate-vote_sent", 1);
vote_blob_sender.send(vec![shared_blob])?;
}
Ok(())
}
#[cfg(test)]
pub mod tests {
use super::*;
use bank::Bank;
use bincode::deserialize;
use budget_instruction::Vote;
use cluster_info::{ClusterInfo, NodeInfo};
use entry::next_entry;
use hash::{hash, Hash};
use logger;
use mint::Mint;
use std::sync::mpsc::channel;
use std::sync::{Arc, RwLock};
use std::thread::sleep;
use std::time::Duration;
use system_transaction::SystemTransaction;
use transaction::Transaction;
#[test]
fn test_send_leader_vote() {
logger::setup();
// create a mint/bank
let mint = Mint::new(1000);
let bank = Arc::new(Bank::new(&mint));
let hash0 = Hash::default();
// get a non-default hash last_id
let entry = next_entry(&hash0, 1, vec![]);
bank.register_entry_id(&entry.id);
// Create a leader
let leader_data = NodeInfo::new_with_socketaddr(&"127.0.0.1:1234".parse().unwrap());
let leader_pubkey = leader_data.id.clone();
let mut leader_cluster_info = ClusterInfo::new(leader_data).unwrap();
// give the leader some tokens
let give_leader_tokens_tx =
Transaction::system_new(&mint.keypair(), leader_pubkey.clone(), 100, entry.id);
bank.process_transaction(&give_leader_tokens_tx).unwrap();
leader_cluster_info.set_leader(leader_pubkey);
// Insert 7 agreeing validators / 3 disagreeing
// and votes for new last_id
for i in 0..10 {
let mut validator =
NodeInfo::new_with_socketaddr(&format!("127.0.0.1:234{}", i).parse().unwrap());
let vote = Vote {
version: validator.version + 1,
contact_info_version: 1,
};
if i < 7 {
validator.ledger_state.last_id = entry.id;
}
leader_cluster_info.insert(&validator);
trace!("validator id: {:?}", validator.id);
leader_cluster_info.insert_vote(&validator.id, &vote, entry.id);
}
let leader = Arc::new(RwLock::new(leader_cluster_info));
let (vote_blob_sender, vote_blob_receiver) = channel();
let mut last_vote: u64 = timing::timestamp() - VOTE_TIMEOUT_MS - 1;
let mut last_valid_validator_timestamp = 0;
let res = send_leader_vote(
&mint.pubkey(),
&mint.keypair(),
&bank,
&leader,
&vote_blob_sender,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
trace!("vote result: {:?}", res);
assert!(res.is_ok());
let vote_blob = vote_blob_receiver.recv_timeout(Duration::from_millis(500));
trace!("vote_blob: {:?}", vote_blob);
// leader shouldn't vote yet, not enough votes
assert!(vote_blob.is_err());
// add two more nodes and see that it succeeds
for i in 0..2 {
let mut validator =
NodeInfo::new_with_socketaddr(&format!("127.0.0.1:234{}", i).parse().unwrap());
let vote = Vote {
version: validator.version + 1,
contact_info_version: 1,
};
validator.ledger_state.last_id = entry.id;
leader.write().unwrap().insert(&validator);
trace!("validator id: {:?}", validator.id);
leader
.write()
.unwrap()
.insert_vote(&validator.id, &vote, entry.id);
}
last_vote = timing::timestamp() - VOTE_TIMEOUT_MS - 1;
let res = send_leader_vote(
&Pubkey::default(),
&mint.keypair(),
&bank,
&leader,
&vote_blob_sender,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
trace!("vote result: {:?}", res);
assert!(res.is_ok());
let vote_blob = vote_blob_receiver.recv_timeout(Duration::from_millis(500));
trace!("vote_blob: {:?}", vote_blob);
// leader should vote now
assert!(vote_blob.is_ok());
// vote should be valid
let blob = &vote_blob.unwrap()[0];
let tx = deserialize(&(blob.read().unwrap().data)).unwrap();
assert_eq!(bank.process_transaction(&tx), Ok(()));
}
#[test]
fn test_get_last_id_to_vote_on() {
logger::setup();
let mint = Mint::new(1234);
let bank = Arc::new(Bank::new(&mint));
let mut last_vote = 0;
let mut last_valid_validator_timestamp = 0;
// generate 10 last_ids, register 6 with the bank
let ids: Vec<_> = (0..10)
.map(|i| {
let last_id = hash(&serialize(&i).unwrap()); // Unique hash
if i < 6 {
bank.register_entry_id(&last_id);
}
// sleep to get a different timestamp in the bank
sleep(Duration::from_millis(1));
last_id
}).collect();
// see that we fail to have 2/3rds consensus
assert!(
get_last_id_to_vote_on(
&Pubkey::default(),
&ids,
&bank,
0,
&mut last_vote,
&mut last_valid_validator_timestamp
).is_err()
);
// register another, see passing
bank.register_entry_id(&ids[6]);
let res = get_last_id_to_vote_on(
&Pubkey::default(),
&ids,
&bank,
0,
&mut last_vote,
&mut last_valid_validator_timestamp,
);
if let Ok((hash, timestamp)) = res {
assert!(hash == ids[6]);
assert!(timestamp != 0);
} else {
assert!(false, "get_last_id returned error!: {:?}", res);
}
}
}
|
#![doc(html_root_url="https://arcnmx.github.io/serde-value")]
extern crate serde;
extern crate ordered_float;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::cmp::Ordering;
use serde::{de, Deserialize, Serialize, Serializer};
use ordered_float::OrderedFloat;
#[macro_use]
mod forward;
#[derive(Debug)]
pub enum DeserializerError {
Custom(String),
EndOfStream,
InvalidType(de::Type),
InvalidValue(String),
InvalidLength(usize),
UnknownVariant(String),
UnknownField(String),
MissingField(&'static str),
}
impl de::Error for DeserializerError {
fn custom<T: Into<String>>(msg: T) -> Self {
DeserializerError::Custom(msg.into())
}
fn end_of_stream() -> Self {
DeserializerError::EndOfStream
}
fn invalid_type(ty: de::Type) -> Self {
DeserializerError::InvalidType(ty)
}
fn invalid_value(msg: &str) -> Self {
DeserializerError::InvalidValue(msg.into())
}
fn invalid_length(len: usize) -> Self {
DeserializerError::InvalidLength(len)
}
fn unknown_variant(field: &str) -> Self {
DeserializerError::UnknownVariant(field.into())
}
fn unknown_field(field: &str) -> Self {
DeserializerError::UnknownField(field.into())
}
fn missing_field(field: &'static str) -> Self {
DeserializerError::MissingField(field)
}
}
impl DeserializerError {
pub fn to_error<E: de::Error>(&self) -> E {
match *self {
DeserializerError::Custom(ref msg) => E::custom(msg.clone()),
DeserializerError::EndOfStream => E::end_of_stream(),
DeserializerError::InvalidType(ty) => E::invalid_type(ty),
DeserializerError::InvalidValue(ref msg) => E::invalid_value(msg),
DeserializerError::InvalidLength(len) => E::invalid_length(len),
DeserializerError::UnknownVariant(ref field) => E::unknown_variant(field),
DeserializerError::UnknownField(ref field) => E::unknown_field(field),
DeserializerError::MissingField(field) => E::missing_field(field),
}
}
pub fn into_error<E: de::Error>(self) -> E {
self.to_error()
}
}
impl Error for DeserializerError {
fn description(&self) -> &str {
"Value deserializer error"
}
}
impl fmt::Display for DeserializerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DeserializerError::Custom(ref msg) => write!(f, "{}", msg),
DeserializerError::EndOfStream => write!(f, "End of stream"),
DeserializerError::InvalidType(ty) => write!(f, "Invalid type. Expected {:?}", ty),
DeserializerError::InvalidValue(ref msg) => write!(f, "Invalid value: {}", msg),
DeserializerError::InvalidLength(len) => write!(f, "Invalid length: {}", len),
DeserializerError::UnknownVariant(ref field) => write!(f, "Unknown variant: {}", field),
DeserializerError::UnknownField(ref field) => write!(f, "Unknown field: {}", field),
DeserializerError::MissingField(field) => write!(f, "Missing field: {}", field),
}
}
}
impl From<de::value::Error> for DeserializerError {
fn from(e: de::value::Error) -> Self {
match e {
de::value::Error::Custom(msg) => DeserializerError::Custom(msg),
de::value::Error::InvalidType(ty) => DeserializerError::InvalidType(ty),
de::value::Error::InvalidLength(len) => DeserializerError::InvalidLength(len),
de::value::Error::InvalidValue(msg) => DeserializerError::InvalidValue(msg),
de::value::Error::EndOfStream => DeserializerError::EndOfStream,
de::value::Error::UnknownVariant(field) => DeserializerError::UnknownVariant(field),
de::value::Error::UnknownField(field) => DeserializerError::UnknownField(field),
de::value::Error::MissingField(field) => DeserializerError::MissingField(field),
}
}
}
#[derive(Clone, Debug)]
pub enum Value {
Bool(bool),
Usize(usize),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
Isize(isize),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Char(char),
String(String),
Unit,
UnitStruct(&'static str),
Option(Option<Box<Value>>),
Newtype(Box<Value>),
Seq(Vec<Value>),
Map(BTreeMap<Value, Value>),
Bytes(Vec<u8>),
}
impl PartialEq for Value {
fn eq(&self, rhs: &Self) -> bool {
match (self, rhs) {
(&Value::Bool(v0), &Value::Bool(v1)) if v0 == v1 => true,
(&Value::Usize(v0), &Value::Usize(v1)) if v0 == v1 => true,
(&Value::U8(v0), &Value::U8(v1)) if v0 == v1 => true,
(&Value::U16(v0), &Value::U16(v1)) if v0 == v1 => true,
(&Value::U32(v0), &Value::U32(v1)) if v0 == v1 => true,
(&Value::U64(v0), &Value::U64(v1)) if v0 == v1 => true,
(&Value::Isize(v0), &Value::Isize(v1)) if v0 == v1 => true,
(&Value::I8(v0), &Value::I8(v1)) if v0 == v1 => true,
(&Value::I16(v0), &Value::I16(v1)) if v0 == v1 => true,
(&Value::I32(v0), &Value::I32(v1)) if v0 == v1 => true,
(&Value::I64(v0), &Value::I64(v1)) if v0 == v1 => true,
(&Value::F32(v0), &Value::F32(v1)) if OrderedFloat(v0) == OrderedFloat(v1) => true,
(&Value::F64(v0), &Value::F64(v1)) if OrderedFloat(v0) == OrderedFloat(v1) => true,
(&Value::Char(v0), &Value::Char(v1)) if v0 == v1 => true,
(&Value::String(ref v0), &Value::String(ref v1)) if v0 == v1 => true,
(&Value::Unit, &Value::Unit) => true,
(&Value::UnitStruct(v0), &Value::UnitStruct(v1)) if v0 == v1 => true,
(&Value::Option(ref v0), &Value::Option(ref v1)) if v0 == v1 => true,
(&Value::Newtype(ref v0), &Value::Newtype(ref v1)) if v0 == v1 => true,
(&Value::Seq(ref v0), &Value::Seq(ref v1)) if v0 == v1 => true,
(&Value::Map(ref v0), &Value::Map(ref v1)) if v0 == v1 => true,
(&Value::Bytes(ref v0), &Value::Bytes(ref v1)) if v0 == v1 => true,
_ => false,
}
}
}
impl Ord for Value {
fn cmp(&self, rhs: &Self) -> Ordering {
match (self, rhs) {
(&Value::Bool(v0), &Value::Bool(ref v1)) => v0.cmp(v1),
(&Value::Usize(v0), &Value::Usize(ref v1)) => v0.cmp(v1),
(&Value::U8(v0), &Value::U8(ref v1)) => v0.cmp(v1),
(&Value::U16(v0), &Value::U16(ref v1)) => v0.cmp(v1),
(&Value::U32(v0), &Value::U32(ref v1)) => v0.cmp(v1),
(&Value::U64(v0), &Value::U64(ref v1)) => v0.cmp(v1),
(&Value::Isize(v0), &Value::Isize(ref v1)) => v0.cmp(v1),
(&Value::I8(v0), &Value::I8(ref v1)) => v0.cmp(v1),
(&Value::I16(v0), &Value::I16(ref v1)) => v0.cmp(v1),
(&Value::I32(v0), &Value::I32(ref v1)) => v0.cmp(v1),
(&Value::I64(v0), &Value::I64(ref v1)) => v0.cmp(v1),
(&Value::F32(v0), &Value::F32(v1)) => OrderedFloat(v0).cmp(&OrderedFloat(v1)),
(&Value::F64(v0), &Value::F64(v1)) => OrderedFloat(v0).cmp(&OrderedFloat(v1)),
(&Value::Char(v0), &Value::Char(ref v1)) => v0.cmp(v1),
(&Value::String(ref v0), &Value::String(ref v1)) => v0.cmp(v1),
(&Value::Unit, &Value::Unit) => Ordering::Equal,
(&Value::UnitStruct(v0), &Value::UnitStruct(v1)) => v0.cmp(v1),
(&Value::Option(ref v0), &Value::Option(ref v1)) => v0.cmp(v1),
(&Value::Newtype(ref v0), &Value::Newtype(ref v1)) => v0.cmp(v1),
(&Value::Seq(ref v0), &Value::Seq(ref v1)) => v0.cmp(v1),
(&Value::Map(ref v0), &Value::Map(ref v1)) => v0.cmp(v1),
(&Value::Bytes(ref v0), &Value::Bytes(ref v1)) => v0.cmp(v1),
(ref v0, ref v1) => v0.discriminant().cmp(&v1.discriminant()),
}
}
}
impl Value {
fn discriminant(&self) -> usize {
match *self {
Value::Bool(..) => 0,
Value::Usize(..) => 1,
Value::U8(..) => 2,
Value::U16(..) => 3,
Value::U32(..) => 4,
Value::U64(..) => 5,
Value::Isize(..) => 6,
Value::I8(..) => 7,
Value::I16(..) => 8,
Value::I32(..) => 9,
Value::I64(..) => 10,
Value::F32(..) => 11,
Value::F64(..) => 12,
Value::Char(..) => 13,
Value::String(..) => 14,
Value::Unit => 15,
Value::UnitStruct(..) => 16,
Value::Option(..) => 17,
Value::Newtype(..) => 18,
Value::Seq(..) => 19,
Value::Map(..) => 20,
Value::Bytes(..) => 21,
}
}
pub fn deserializer(self) -> Deserializer {
Deserializer::new(self)
}
pub fn deserialize_into<T: Deserialize>(self) -> Result<T, DeserializerError> {
T::deserialize(&mut self.deserializer())
}
}
impl Eq for Value { }
impl PartialOrd for Value {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
pub struct ValueVisitor;
impl de::Visitor for ValueVisitor {
type Value = Value;
fn visit_bool<E>(&mut self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_usize<E>(&mut self, value: usize) -> Result<Value, E> {
Ok(Value::Usize(value))
}
fn visit_isize<E>(&mut self, value: isize) -> Result<Value, E> {
Ok(Value::Isize(value))
}
fn visit_i8<E>(&mut self, value: i8) -> Result<Value, E> {
Ok(Value::I8(value))
}
fn visit_i16<E>(&mut self, value: i16) -> Result<Value, E> {
Ok(Value::I16(value))
}
fn visit_i32<E>(&mut self, value: i32) -> Result<Value, E> {
Ok(Value::I32(value))
}
fn visit_i64<E>(&mut self, value: i64) -> Result<Value, E> {
Ok(Value::I64(value))
}
fn visit_u8<E>(&mut self, value: u8) -> Result<Value, E> {
Ok(Value::U8(value))
}
fn visit_u16<E>(&mut self, value: u16) -> Result<Value, E> {
Ok(Value::U16(value))
}
fn visit_u32<E>(&mut self, value: u32) -> Result<Value, E> {
Ok(Value::U32(value))
}
fn visit_u64<E>(&mut self, value: u64) -> Result<Value, E> {
Ok(Value::U64(value))
}
fn visit_f32<E>(&mut self, value: f32) -> Result<Value, E> {
Ok(Value::F32(value))
}
fn visit_f64<E>(&mut self, value: f64) -> Result<Value, E> {
Ok(Value::F64(value))
}
fn visit_char<E>(&mut self, value: char) -> Result<Value, E> {
Ok(Value::Char(value))
}
fn visit_str<E>(&mut self, value: &str) -> Result<Value, E> {
Ok(Value::String(value.into()))
}
fn visit_string<E>(&mut self, value: String) -> Result<Value, E> {
Ok(Value::String(value))
}
fn visit_unit<E>(&mut self) -> Result<Value, E> {
Ok(Value::Unit)
}
fn visit_unit_struct<E>(&mut self, name: &'static str) -> Result<Value, E> {
Ok(Value::UnitStruct(name))
}
fn visit_none<E>(&mut self) -> Result<Value, E> {
Ok(Value::Option(None))
}
fn visit_some<D: de::Deserializer>(&mut self, d: &mut D) -> Result<Value, D::Error> {
d.deserialize(ValueVisitor).map(|v| Value::Option(Some(Box::new(v))))
}
fn visit_newtype_struct<D: de::Deserializer>(&mut self, d: &mut D) -> Result<Value, D::Error> {
d.deserialize(ValueVisitor).map(|v| Value::Newtype(Box::new(v)))
}
fn visit_seq<V: de::SeqVisitor>(&mut self, visitor: V) -> Result<Value, V::Error> {
let values = try!(de::impls::VecVisitor::new().visit_seq(visitor));
Ok(Value::Seq(values))
}
fn visit_map<V: de::MapVisitor>(&mut self, visitor: V) -> Result<Value, V::Error> {
let mut v = de::impls::BTreeMapVisitor::new();
let values = try!(v.visit_map(visitor));
Ok(Value::Map(values))
}
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Value, E> {
Ok(Value::Bytes(v.into()))
}
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Value, E> {
Ok(Value::Bytes(v))
}
}
impl Deserialize for Value {
fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<Self, D::Error> {
d.deserialize(ValueVisitor)
}
}
impl Serialize for Value {
fn serialize<S: Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
match self {
&Value::Bool(v) => s.serialize_bool(v),
&Value::Usize(v) => s.serialize_usize(v),
&Value::U8(v) => s.serialize_u8(v),
&Value::U16(v) => s.serialize_u16(v),
&Value::U32(v) => s.serialize_u32(v),
&Value::U64(v) => s.serialize_u64(v),
&Value::Isize(v) => s.serialize_isize(v),
&Value::I8(v) => s.serialize_i8(v),
&Value::I16(v) => s.serialize_i16(v),
&Value::I32(v) => s.serialize_i32(v),
&Value::I64(v) => s.serialize_i64(v),
&Value::F32(v) => s.serialize_f32(v),
&Value::F64(v) => s.serialize_f64(v),
&Value::Char(v) => s.serialize_char(v),
&Value::String(ref v) => s.serialize_str(v),
&Value::Unit => s.serialize_unit(),
&Value::UnitStruct(name) => s.serialize_unit_struct(name),
&Value::Option(None) => s.serialize_none(),
&Value::Option(Some(ref v)) => s.serialize_some(v),
&Value::Newtype(ref v) => s.serialize_newtype_struct("", v),
&Value::Seq(ref v) => v.serialize(s),
&Value::Map(ref v) => v.serialize(s),
&Value::Bytes(ref v) => s.serialize_bytes(v),
}
}
}
pub struct Deserializer {
pub value: Option<Value>,
}
impl Deserializer {
pub fn new(value: Value) -> Self {
Deserializer {
value: Some(value),
}
}
}
impl de::value::ValueDeserializer for Value {
type Deserializer = ValueDeserializer;
fn into_deserializer(self) -> Self::Deserializer {
ValueDeserializer(Deserializer::new(self))
}
}
struct MapVisitor<'a, I> {
iter: I,
de: &'a mut Deserializer,
value: Option<Value>,
}
impl<'a, I: Iterator<Item=(Value, Value)>> de::MapVisitor for MapVisitor<'a, I> {
type Error = DeserializerError;
fn visit_key<K: Deserialize>(&mut self) -> Result<Option<K>, Self::Error> {
while let Some((k, v)) = self.iter.next() {
let mut de = Deserializer::new(k.clone());
return match Deserialize::deserialize(&mut de) {
Ok(k) => {
self.value = Some(v);
Ok(Some(k))
},
Err(DeserializerError::UnknownField(..)) => {
self.de.borrow_map().insert(k, v);
continue
},
Err(e) => Err(e),
};
}
Ok(None)
}
fn visit_value<V: Deserialize>(&mut self) -> Result<V, Self::Error> {
match self.value.take() {
Some(v) => V::deserialize(&mut Deserializer::new(v)),
None => Err(de::Error::end_of_stream())
}
}
fn end(&mut self) -> Result<(), Self::Error> {
self.de.borrow_map().extend(&mut self.iter);
Ok(())
}
fn missing_field<V: Deserialize>(&mut self, field: &'static str) -> Result<V, Self::Error> {
struct MissingFieldDeserializer(&'static str);
impl de::Deserializer for MissingFieldDeserializer {
type Error = DeserializerError;
fn deserialize<V: de::Visitor>(&mut self,
_visitor: V)
-> Result<V::Value, Self::Error> {
Err(DeserializerError::MissingField(self.0))
}
fn deserialize_option<V: de::Visitor>(&mut self,
mut visitor: V)
-> Result<V::Value, Self::Error> {
visitor.visit_none()
}
forward_to_deserialize!{
deserialize_bool();
deserialize_usize();
deserialize_u8();
deserialize_u16();
deserialize_u32();
deserialize_u64();
deserialize_isize();
deserialize_i8();
deserialize_i16();
deserialize_i32();
deserialize_i64();
deserialize_f32();
deserialize_f64();
deserialize_char();
deserialize_str();
deserialize_string();
deserialize_unit();
deserialize_seq();
deserialize_seq_fixed_size(len: usize);
deserialize_bytes();
deserialize_map();
deserialize_unit_struct(name: &'static str);
deserialize_newtype_struct(name: &'static str);
deserialize_tuple_struct(name: &'static str, len: usize);
deserialize_struct(name: &'static str, fields: &'static [&'static str]);
deserialize_struct_field();
deserialize_tuple(len: usize);
deserialize_enum(name: &'static str, variants: &'static [&'static str]);
deserialize_ignored_any();
}
}
let mut de = MissingFieldDeserializer(field);
Ok(try!(de::Deserialize::deserialize(&mut de)))
}
}
impl Deserializer {
fn borrow_map(&mut self) -> &mut BTreeMap<Value, Value> {
self.value = self.value.take().or(Some(Value::Map(BTreeMap::new())));
match *self.value.as_mut().unwrap() {
Value::Map(ref mut map) => map,
_ => unreachable!(),
}
}
}
impl de::Deserializer for Deserializer {
type Error = DeserializerError;
fn deserialize<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
if let Some(value) = self.value.take() {
match value {
Value::Bool(v) => visitor.visit_bool(v),
Value::Usize(v) => visitor.visit_usize(v),
Value::U8(v) => visitor.visit_u8(v),
Value::U16(v) => visitor.visit_u16(v),
Value::U32(v) => visitor.visit_u32(v),
Value::U64(v) => visitor.visit_u64(v),
Value::Isize(v) => visitor.visit_isize(v),
Value::I8(v) => visitor.visit_i8(v),
Value::I16(v) => visitor.visit_i16(v),
Value::I32(v) => visitor.visit_i32(v),
Value::I64(v) => visitor.visit_i64(v),
Value::F32(v) => visitor.visit_f32(v),
Value::F64(v) => visitor.visit_f64(v),
Value::Char(v) => visitor.visit_char(v),
Value::String(v) => visitor.visit_string(v),
Value::Unit => visitor.visit_unit(),
Value::UnitStruct(name) => visitor.visit_unit_struct(name),
Value::Option(None) => visitor.visit_none(),
Value::Option(Some(v)) => visitor.visit_some(&mut Deserializer::new(*v)),
Value::Newtype(v) => visitor.visit_newtype_struct(&mut Deserializer::new(*v)),
Value::Seq(v) => {
let len = v.len();
visitor.visit_seq(de::value::SeqDeserializer::new(v.into_iter(), len)).map_err(From::from)
},
Value::Map(v) => {
visitor.visit_map(MapVisitor {
iter: v.into_iter(),
de: self,
value: None,
})
},
Value::Bytes(v) => visitor.visit_byte_buf(v),
}
} else {
Err(de::Error::end_of_stream())
}
}
fn deserialize_option<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
match self.value {
Some(Value::Option(..)) => self.deserialize(visitor),
Some(Value::Unit) => {
self.value.take();
visitor.visit_none()
},
_ => visitor.visit_some(self)
}
}
forward_to_deserialize!{
deserialize_bool();
deserialize_usize();
deserialize_u8();
deserialize_u16();
deserialize_u32();
deserialize_u64();
deserialize_isize();
deserialize_i8();
deserialize_i16();
deserialize_i32();
deserialize_i64();
deserialize_f32();
deserialize_f64();
deserialize_char();
deserialize_str();
deserialize_string();
deserialize_unit();
deserialize_seq();
deserialize_seq_fixed_size(len: usize);
deserialize_bytes();
deserialize_map();
deserialize_unit_struct(name: &'static str);
deserialize_newtype_struct(name: &'static str);
deserialize_tuple_struct(name: &'static str, len: usize);
deserialize_struct(name: &'static str, fields: &'static [&'static str]);
deserialize_struct_field();
deserialize_tuple(len: usize);
deserialize_enum(name: &'static str, variants: &'static [&'static str]);
deserialize_ignored_any();
}
}
pub struct ValueDeserializer(Deserializer);
impl de::Deserializer for ValueDeserializer {
type Error = de::value::Error;
fn deserialize<V: de::Visitor>(&mut self, visitor: V) -> Result<V::Value, Self::Error> {
self.0.deserialize(visitor).map_err(DeserializerError::into_error)
}
forward_to_deserialize!{
deserialize_bool();
deserialize_usize();
deserialize_u8();
deserialize_u16();
deserialize_u32();
deserialize_u64();
deserialize_isize();
deserialize_i8();
deserialize_i16();
deserialize_i32();
deserialize_i64();
deserialize_f32();
deserialize_f64();
deserialize_char();
deserialize_str();
deserialize_string();
deserialize_unit();
deserialize_seq();
deserialize_seq_fixed_size(len: usize);
deserialize_bytes();
deserialize_map();
deserialize_option();
deserialize_unit_struct(name: &'static str);
deserialize_newtype_struct(name: &'static str);
deserialize_tuple_struct(name: &'static str, len: usize);
deserialize_struct(name: &'static str, fields: &'static [&'static str]);
deserialize_struct_field();
deserialize_tuple(len: usize);
deserialize_enum(name: &'static str, variants: &'static [&'static str]);
deserialize_ignored_any();
}
}
|
pub mod m2;
pub mod m3;
pub mod m4;
use crate::float::Float;
use std::ops::Div;
#[derive(Default, Copy, Clone, PartialEq, Debug)]
pub struct M2<T>(pub [[T; 2]; 2]);
#[derive(Default, Copy, Clone, PartialEq, Debug)]
pub struct M3<T>(pub [[T; 3]; 3]);
#[derive(Default, Copy, Clone, PartialEq, Debug)]
pub struct M4<T>(pub [[T; 4]; 4]);
pub trait Matrix {
fn transpose(&mut self);
}
pub trait FloatMatrix<F>: Matrix
where
F: Float,
Self: Clone + Div<F, Output = Self>,
{
fn determinant(&self) -> F;
fn cofactor(&self) -> Self;
fn inverse(&self) -> Self {
self.cofactor() / self.determinant()
}
}
pub trait IntoVectors<V> {
fn into_cols(&self) -> V;
fn into_rows(&self) -> V;
}
pub trait FromVectors<V> {
fn from_cols(v: V) -> Self;
fn from_rows(v: V) -> Self;
}
|
use dashmap::DashMap;
use futures::stream::StreamExt;
use rosu_v2::prelude::GameMode;
use twilight_model::id::{
marker::{GuildMarker, UserMarker},
Id,
};
use crate::{
commands::osu::ProfileSize,
database::{
models::{EmbedsSize, OsuData},
GuildConfig, MinimizedPp, UserConfig,
},
BotResult, Database,
};
impl Database {
#[cold]
pub async fn get_guilds(&self) -> BotResult<DashMap<Id<GuildMarker>, GuildConfig>> {
let mut stream = sqlx::query!("SELECT * FROM guild_configs").fetch(&self.pool);
let guilds = DashMap::with_capacity(10_000);
while let Some(entry) = stream.next().await.transpose()? {
let config = GuildConfig {
authorities: serde_cbor::from_slice(&entry.authorities)?,
embeds_size: entry.embeds_size.map(EmbedsSize::from),
minimized_pp: entry.minimized_pp.map(MinimizedPp::from),
prefixes: serde_cbor::from_slice(&entry.prefixes)?,
profile_size: entry.profile_size.map(ProfileSize::from),
show_retries: entry.show_retries,
track_limit: entry.track_limit.map(|limit| limit as u8),
with_lyrics: entry.with_lyrics,
};
guilds.insert(Id::new(entry.guild_id as u64), config);
}
Ok(guilds)
}
pub async fn upsert_guild_config(
&self,
guild_id: Id<GuildMarker>,
config: &GuildConfig,
) -> BotResult<()> {
let query = sqlx::query!(
"INSERT INTO guild_configs (\
guild_id,\
authorities,\
embeds_size,\
minimized_pp,\
prefixes,\
profile_size,\
show_retries,\
track_limit,\
with_lyrics\
)\
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (guild_id) DO \
UPDATE \
SET authorities=$2,\
embeds_size=$3,\
minimized_pp=$4,\
prefixes=$5,\
profile_size=$6,\
show_retries=$7,\
track_limit=$8,\
with_lyrics=$9",
guild_id.get() as i64,
serde_cbor::to_vec(&config.authorities)?,
config.embeds_size.map(|size| size as u8 as i16),
config.minimized_pp.map(|pp| pp as u8 as i16),
serde_cbor::to_vec(&config.prefixes)?,
config.profile_size.map(|size| size as i16),
config.show_retries,
config.track_limit.map(|limit| limit as i16),
config.with_lyrics,
);
query.execute(&self.pool).await?;
info!("Inserted GuildConfig for guild {guild_id} into DB");
Ok(())
}
pub async fn get_user_osu(&self, user_id: Id<UserMarker>) -> BotResult<Option<OsuData>> {
let query = sqlx::query!(
"SELECT user_id,username \
FROM\
(SELECT osu_id \
FROM user_configs \
WHERE discord_id=$1) AS config \
JOIN osu_user_names AS names ON config.osu_id=names.user_id",
user_id.get() as i64
);
match query.fetch_optional(&self.pool).await? {
Some(entry) => {
let osu = OsuData::User {
user_id: entry.user_id as u32,
username: entry.username.into(),
};
Ok(Some(osu))
}
None => Ok(None),
}
}
pub async fn get_user_config(&self, user_id: Id<UserMarker>) -> BotResult<Option<UserConfig>> {
let query = sqlx::query!(
"SELECT * \
FROM\
(SELECT * \
FROM user_configs \
WHERE discord_id=$1) AS config \
JOIN osu_user_names AS names ON config.osu_id=names.user_id",
user_id.get() as i64
);
match query.fetch_optional(&self.pool).await? {
Some(entry) => {
let osu = OsuData::User {
user_id: entry.user_id as u32,
username: entry.username.into(),
};
let config = UserConfig {
embeds_size: entry.embeds_size.map(EmbedsSize::from),
minimized_pp: entry.minimized_pp.map(MinimizedPp::from),
mode: entry.mode.map(|mode| mode as u8).map(GameMode::from),
osu: Some(osu),
profile_size: entry.profile_size.map(ProfileSize::from),
show_retries: entry.show_retries,
twitch_id: entry.twitch_id.map(|id| id as u64),
};
Ok(Some(config))
}
None => Ok(None),
}
}
pub async fn get_user_config_by_osu(&self, username: &str) -> BotResult<Option<UserConfig>> {
let query = sqlx::query!(
"SELECT * \
FROM\
(SELECT user_id \
FROM osu_user_names \
WHERE username=$1) AS user_ids \
JOIN user_configs ON user_ids.user_id=user_configs.osu_id",
username
);
match query.fetch_optional(&self.pool).await? {
Some(entry) => {
let osu = OsuData::User {
user_id: entry.user_id as u32,
username: username.into(),
};
let config = UserConfig {
embeds_size: entry.embeds_size.map(EmbedsSize::from),
minimized_pp: entry.minimized_pp.map(MinimizedPp::from),
mode: entry.mode.map(|mode| mode as u8).map(GameMode::from),
osu: Some(osu),
profile_size: entry.profile_size.map(ProfileSize::from),
show_retries: entry.show_retries,
twitch_id: entry.twitch_id.map(|id| id as u64),
};
Ok(Some(config))
}
None => Ok(None),
}
}
pub async fn insert_user_config(
&self,
user_id: Id<UserMarker>,
config: &UserConfig,
) -> BotResult<()> {
if let Some(OsuData::User { user_id, username }) = &config.osu {
self.upsert_osu_name(*user_id, username).await?;
}
let query = sqlx::query!(
"INSERT INTO user_configs (\
discord_id,\
embeds_size,\
minimized_pp,\
mode,\
osu_id,\
profile_size,\
show_retries,\
twitch_id\
)\
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (discord_id) DO \
UPDATE \
SET embeds_size=$2,\
minimized_pp=$3,\
mode=$4,\
osu_id=$5,\
profile_size=$6,\
show_retries=$7,\
twitch_id=$8",
user_id.get() as i64,
config.embeds_size.map(|size| size as u8 as i16),
config.minimized_pp.map(|pp| pp as u8 as i16),
config.mode.map(|m| m as i16),
config
.osu
.as_ref()
.and_then(OsuData::user_id)
.map(|id| id as i32),
config.profile_size.map(|size| size as i16),
config.show_retries,
config.twitch_id.map(|id| id as i64)
);
query.execute(&self.pool).await?;
debug!("Inserted UserConfig for user {user_id} into DB");
Ok(())
}
pub async fn upsert_osu_name(&self, user_id: u32, username: &str) -> BotResult<()> {
let query = sqlx::query!(
"INSERT INTO osu_user_names (user_id,username)\
VALUES ($1,$2) ON CONFLICT (user_id) DO \
UPDATE \
SET username=$2",
user_id as i32,
username,
);
query.execute(&self.pool).await?;
Ok(())
}
pub async fn get_discord_from_osu_id(&self, user_id: u32) -> BotResult<Option<Id<UserMarker>>> {
let query = sqlx::query!(
"SELECT discord_id FROM user_configs WHERE osu_id=$1",
user_id as i32
);
let discord_id = query
.fetch_optional(&self.pool)
.await?
.map(|e| Id::new(e.discord_id as u64));
Ok(discord_id)
}
}
|
pub mod cert;
pub mod service;
use anyhow::anyhow;
use reqwest::Url;
use tokio::sync::oneshot;
use dialoguer::Confirm;
use indicatif::ProgressBar;
use crate::{
mitm::{cert::setup_certificate, service::make_mitm_server},
style::{SPINNER_STYLE, THEME},
};
pub const DOMAIN_INTERCEPT: &[&str] = &["hk4e-api.mihoyo.com", "hk4e-api-os.mihoyo.com"];
pub const PAGE_INTERCEPT_SUFFIX: &str = "/getGachaLog";
/// Set up proxy server to tap connection and look for gacha url
pub async fn tap_for_url() -> anyhow::Result<Url> {
let (certificate, private_key) = setup_certificate()?;
let (mut receiver, server) = make_mitm_server(certificate, private_key);
let server_addr = server.local_addr();
#[cfg(target_os = "windows")]
let old_proxy_settings = {
// Under windows, ask user whether system proxy should be automatically set
if Confirm::with_theme(&*THEME)
.with_prompt("是否自动配置系统HTTP代理")
.wait_for_newline(true)
.default(true)
.interact()?
{
use proxyconf::internet_settings::modern::{
empty_config,
registry::{self, get_current_user_location},
};
use std::{
process::Command,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
// add certificate to user root store
Command::new("certutil")
.args(&["-user", "-addstore", "root", cert::CERT_FILENAME])
.output()
.ok();
let mut proxy_config = empty_config();
proxy_config.use_manual_proxy = true;
proxy_config.manual_proxy_address = format!("127.0.0.1:{}", server_addr.port());
proxy_config.manual_proxy_bypass_list = "*.local".to_owned();
let proxy_location = get_current_user_location();
let old_proxy_settings =
registry::read_full(&proxy_location).map_err(|e| anyhow!(format!("{}", e)))?;
registry::write(&proxy_location, proxy_config)
.map_err(|e| anyhow!(format!("{}", e)))?;
let need_restore = Arc::new(AtomicBool::new(true));
let need_restore_2 = need_restore.clone();
let old_proxy_settings_2 = old_proxy_settings.clone();
ctrlc::set_handler(move || {
if need_restore_2.load(Ordering::SeqCst) {
registry::write_full(&proxy_location, &old_proxy_settings_2).ok();
}
std::process::exit(0);
})?;
Some((old_proxy_settings, need_restore))
} else {
None
}
};
let pb = ProgressBar::new_spinner()
.with_style(SPINNER_STYLE.clone().template("{spinner:.green} {msg}"));
pb.enable_steady_tick(5);
pb.set_message(&format!(
"HTTP代理已部署在 {},正在等待检测抽卡页面",
server_addr
));
// Spin up the proxy server
let (final_sender, final_receiver) = oneshot::channel();
let server = server.with_graceful_shutdown(async move {
let url = receiver.recv().await;
final_sender.send(url).ok();
});
server.await?;
let url = final_receiver
.await?
.ok_or_else(|| anyhow!("broken pipe of URL retrieval"))?;
#[cfg(target_os = "windows")]
if let Some((old_proxy_settings, need_restore)) = old_proxy_settings {
// Restore proxy settings
use proxyconf::internet_settings::modern::registry::{self, get_current_user_location};
use std::sync::atomic::Ordering;
let proxy_location = get_current_user_location();
registry::write_full(&proxy_location, &old_proxy_settings)
.map_err(|e| anyhow!(format!("{}", e)))?;
need_restore.store(false, Ordering::SeqCst);
}
pb.finish_with_message(&format!("成功获取抽卡页面: {}", url));
Ok(url)
}
|
use colored::Colorize;
use rand::distributions::{Distribution, Uniform};
use reqwest::Error;
use serde::Deserialize;
use crate::api::reformat_search_tags;
use crate::app::Safebooru;
pub fn grab_random_image(args: Safebooru) -> String {
let request_url = evaluate_arguments(&args);
let data = match fetch_api_data(request_url) {
Ok(json_data) => json_data,
Err(error) => {
eprintln!("{}\n", error);
if args.questionable {
println!(
"{}: Couldn't fetch API data. There's probably no \
questionable images associated with your tag(s).",
"help".green()
);
} else {
println!(
"{}: Couldn't fetch API data. Try checking your \
tag(s) for errors.",
"help".green()
);
}
std::process::exit(1);
}
};
let mut rng = rand::thread_rng();
let random_number = Uniform::from(0..data.len());
let index = random_number.sample(&mut rng);
let image = &data[index];
let image_url = format!(
"https://safebooru.org//images/{dir}/{img}?{id}",
dir = image.directory,
img = image.image,
id = image.id
);
if args.details {
let ImageData {
rating,
width,
height,
tags,
..
} = image;
let details = ImageInfo {
url: &image_url,
rating,
width: *width,
height: *height,
tags: tags.split(' ').collect(),
};
match print_image_details(details) {
Ok(_) => (),
Err(error) => {
eprintln!("{}\n", error);
println!(
"{}: There was an error when printing the tags. Please try again later.",
"help".green()
);
std::process::exit(1);
}
}
}
image_url
}
fn evaluate_arguments(args: &Safebooru) -> String {
let Safebooru {
questionable, tags, ..
} = args;
let tags = match tags {
Some(search_items) => search_items,
None => "",
};
let search_tags = String::from(tags);
let mut tags = reformat_search_tags(search_tags);
if *questionable {
tags.push_str("%20rating:questionable");
}
let tags = format!("&tags={}", tags);
// No key needed for access
let mut api =
String::from("https://safebooru.org/index.php?page=dapi&s=post&q=index&limit=100&json=1");
api.push_str(&tags);
api
}
#[derive(Deserialize, Debug)]
struct ImageData {
// Image URL
directory: String,
image: String,
id: u32,
// Image details
rating: String,
width: u32,
height: u32,
tags: String,
}
fn fetch_api_data(url: String) -> Result<Vec<ImageData>, Error> {
let response = reqwest::blocking::get(&url)?;
let data: Vec<ImageData> = response.json()?;
Ok(data)
}
struct ImageInfo<'a> {
url: &'a str,
rating: &'a str,
width: u32,
height: u32,
tags: Vec<&'a str>,
}
fn print_image_details(info: ImageInfo) -> Result<(), Box<dyn std::error::Error>> {
use std::io::{self, Write};
let ImageInfo {
url,
rating,
width,
height,
tags,
} = info;
println!("✉️ {title}: {}", url, title = "Link".cyan());
println!("⚖️ {title}: {}", rating, title = "Rating".cyan());
println!(
"📐 {title}: {w} x {h}",
title = "Dimensions".cyan(),
w = width,
h = height
);
let stdout = io::stdout();
let lock = stdout.lock();
let mut buffer = io::BufWriter::new(lock);
write!(buffer, "🏷️ {}:", "Tags".cyan())?;
tags.iter().try_for_each(|tag| write!(buffer, " {}", tag))?;
writeln!(buffer)?;
Ok(())
}
|
use std::time::Duration;
use green::Callback;
use green::task::spawn;
use rustuv::Timer;
fn sender(tx: Sender<()>) -> Box<Callback + Send> {
struct MySender { tx: Sender<()> }
impl Callback for MySender {
fn call(&mut self) { self.tx.send(()); }
}
box MySender { tx: tx } as Box<Callback + Send>
}
fn ms(n: i64) -> Duration { Duration::milliseconds(n) }
test!(fn test_io_timer_sleep_simple() {
let mut timer = Timer::new().unwrap();
timer.sleep(ms(1));
})
test!(fn test_io_timer_sleep_oneshot() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(1), sender(tx));
rx.recv();
})
test!(fn test_io_timer_sleep_oneshot_forget() {
let mut timer = Timer::new().unwrap();
let (tx, _rx) = channel();
timer.oneshot(ms(100000000), sender(tx));
})
test!(fn oneshot_twice() {
let mut timer = Timer::new().unwrap();
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
timer.oneshot(ms(10000), sender(tx1));
timer.oneshot(ms(1), sender(tx2));
rx2.recv();
assert_eq!(rx1.recv_opt(), Err(()));
})
test!(fn test_io_timer_oneshot_then_sleep() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(100000000), sender(tx));
timer.sleep(ms(1)); // this should invalidate rx
assert_eq!(rx.recv_opt(), Err(()));
})
test!(fn test_io_timer_sleep_periodic() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1), sender(tx));
rx.recv();
rx.recv();
rx.recv();
})
test!(fn test_io_timer_sleep_periodic_forget() {
let mut timer = Timer::new().unwrap();
let (tx, _rx) = channel();
timer.periodic(ms(100000000), sender(tx));
})
test!(fn oneshot() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(1), sender(tx));
rx.recv();
assert!(rx.recv_opt().is_err());
let (tx, rx) = channel();
timer.oneshot(ms(1), sender(tx));
rx.recv();
assert!(rx.recv_opt().is_err());
})
test!(fn overrides() {
let mut timer = Timer::new().unwrap();
let (otx, orx) = channel();
let (ptx, prx) = channel();
timer.oneshot(ms(100), sender(otx));
timer.periodic(ms(100), sender(ptx));
timer.sleep(ms(1));
assert_eq!(orx.recv_opt(), Err(()));
assert_eq!(prx.recv_opt(), Err(()));
let (tx, rx) = channel();
timer.oneshot(ms(1), sender(tx));
rx.recv();
})
test!(fn period() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1), sender(tx));
rx.recv();
rx.recv();
let (tx, rx) = channel();
timer.periodic(ms(1), sender(tx));
rx.recv();
rx.recv();
})
test!(fn sleep() {
let mut timer = Timer::new().unwrap();
timer.sleep(ms(1));
timer.sleep(ms(1));
})
test!(fn oneshot_fail() {
let mut timer = Timer::new().unwrap();
let (tx, _rx) = channel();
timer.oneshot(ms(1), sender(tx));
drop(timer);
})
test!(fn period_fail() {
let mut timer = Timer::new().unwrap();
let (tx, _rx) = channel();
timer.periodic(ms(1), sender(tx));
drop(timer);
})
test!(fn normal_fail() {
let _timer = Timer::new().unwrap();
})
test!(fn closing_channel_during_drop_doesnt_kill_everything() {
// see issue #10375
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1000), sender(tx));
spawn(proc() {
let _ = rx.recv_opt();
});
// when we drop the Timer we're going to destroy the channel,
// which must wake up the task on the other end
})
test!(fn reset_doesnt_switch_tasks() {
// similar test to the one above.
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1000), sender(tx));
spawn(proc() {
let _ = rx.recv_opt();
});
let (tx, _rx) = channel();
timer.oneshot(ms(1), sender(tx));
})
test!(fn reset_doesnt_switch_tasks2() {
// similar test to the one above.
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1000), sender(tx));
spawn(proc() {
let _ = rx.recv_opt();
});
timer.sleep(ms(1));
})
test!(fn sender_goes_away_oneshot() {
let rx = {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(1000), sender(tx));
rx
};
assert_eq!(rx.recv_opt(), Err(()));
})
test!(fn sender_goes_away_period() {
let rx = {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(1000), sender(tx));
rx
};
assert_eq!(rx.recv_opt(), Err(()));
})
test!(fn receiver_goes_away_oneshot() {
let mut timer1 = Timer::new().unwrap();
let (tx, _rx) = channel();
timer1.oneshot(ms(1), sender(tx));
let mut timer2 = Timer::new().unwrap();
// while sleeping, the previous timer should fire and not have its
// callback do something terrible.
timer2.sleep(ms(2));
})
test!(fn receiver_goes_away_period() {
let mut timer1 = Timer::new().unwrap();
let (tx, _rx) = channel();
timer1.periodic(ms(1), sender(tx));
let mut timer2 = Timer::new().unwrap();
// while sleeping, the previous timer should fire and not have its
// callback do something terrible.
timer2.sleep(ms(2));
})
test!(fn sleep_zero() {
let mut timer = Timer::new().unwrap();
timer.sleep(ms(0));
})
test!(fn sleep_negative() {
let mut timer = Timer::new().unwrap();
timer.sleep(ms(-1000000));
})
test!(fn oneshot_zero() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(0), sender(tx));
rx.recv();
})
test!(fn oneshot_negative() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.oneshot(ms(-1000000), sender(tx));
rx.recv();
})
test!(fn periodic_zero() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(0), sender(tx));
rx.recv();
rx.recv();
rx.recv();
rx.recv();
})
test!(fn periodic_negative() {
let mut timer = Timer::new().unwrap();
let (tx, rx) = channel();
timer.periodic(ms(-1000000), sender(tx));
rx.recv();
rx.recv();
rx.recv();
rx.recv();
})
|
use rand::rngs::ThreadRng;
use std::fmt::{self, Display};
use std::iter::Sum;
use std::ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};
use crate::{rand, rand_between};
#[derive(Copy, Clone, Debug)]
pub struct Vec3 {
x: f64,
y: f64,
z: f64,
}
pub type Point3 = Vec3;
pub type Color = Vec3;
impl Vec3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
pub fn rand(rng: &mut ThreadRng) -> Self {
Self {
x: rand(rng),
y: rand(rng),
z: rand(rng),
}
}
pub fn rand_between(min: f64, max: f64, rng: &mut ThreadRng) -> Self {
Self {
x: rand_between(min, max, rng),
y: rand_between(min, max, rng),
z: rand_between(min, max, rng),
}
}
pub fn rand_in_unit_sphere(rng: &mut ThreadRng) -> Self {
loop {
let p = Self::rand_between(-1.0, 1.0, rng);
if p.norm_squared() >= 1.0 {
continue;
}
return p;
}
}
pub fn rand_in_unit_disk(rng: &mut ThreadRng) -> Self {
loop {
let p = Self {
x: rand_between(-1.0, 1.0, rng),
y: rand_between(-1.0, 1.0, rng),
z: 0.0,
};
if p.norm_squared() >= 1.0 {
continue;
}
return p;
}
}
pub fn rand_unit(rng: &mut ThreadRng) -> Self {
Self::rand_in_unit_sphere(rng).normalized()
}
pub fn rand_in_hemisphere(normal: Vec3, rng: &mut ThreadRng) -> Self {
let in_unit = Self::rand_in_unit_sphere(rng);
if Self::dot(in_unit, normal) > 0.0 {
in_unit
} else {
-in_unit
}
}
pub fn x(&self) -> f64 {
self.x
}
pub fn y(&self) -> f64 {
self.y
}
pub fn z(&self) -> f64 {
self.z
}
pub fn norm(self) -> f64 {
f64::sqrt(self.norm_squared())
}
pub fn norm_squared(self) -> f64 {
self.x * self.x + self.y * self.y + self.z * self.z
}
pub fn normalized(self) -> Self {
self / self.norm()
}
pub fn dot(self, other: Self) -> f64 {
self.x * other.x + self.y * other.y + self.z * other.z
}
pub fn cross(self, other: Self) -> Self {
Self {
x: self.y * other.z - self.z * other.y,
y: self.z * other.x - self.x * other.z,
z: self.x * other.y - self.y * other.x,
}
}
pub fn reflect(self, n: Self) -> Self {
self - n * Self::dot(self, n) * 2.0
}
pub fn refract(self, n: Self, eta: f64) -> Self {
let cos_th = f64::min(Self::dot(-self, n), 1.0);
let perp = (self + n * cos_th) * eta;
let par = n * -f64::sqrt(f64::abs(1.0 - perp.norm_squared()));
perp + par
}
pub fn near_zero(self) -> bool {
const S: f64 = 1e-8;
f64::abs(self.x) < S && f64::abs(self.y) < S && f64::abs(self.z) < S
}
pub fn format_color(self, samples_per_pixel: u32) -> String {
let mut r = self.x;
let mut g = self.y;
let mut b = self.z;
let scale = 1.0 / samples_per_pixel as f64;
r = f64::sqrt(scale * r);
g = f64::sqrt(scale * g);
b = f64::sqrt(scale * b);
format!(
"{} {} {}",
(256.0 * r.clamp(0.0, 0.999)) as i32,
(256.0 * g.clamp(0.0, 0.999)) as i32,
(256.0 * b.clamp(0.0, 0.999)) as i32,
)
}
}
impl Default for Vec3 {
fn default() -> Self {
Self {
x: 0.0,
y: 0.0,
z: 0.0,
}
}
}
impl Display for Vec3 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", self.x, self.y, self.z)
}
}
impl Neg for Vec3 {
type Output = Vec3;
fn neg(self) -> Self::Output {
Self::Output {
x: -self.x,
y: -self.y,
z: -self.z,
}
}
}
impl Index<usize> for Vec3 {
type Output = f64;
fn index(&self, index: usize) -> &f64 {
match index {
0 => &self.x,
1 => &self.y,
2 => &self.z,
_ => panic!("Vec3 index out of bounds: got {}", index),
}
}
}
impl IndexMut<usize> for Vec3 {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match index {
0 => &mut self.x,
1 => &mut self.y,
2 => &mut self.z,
_ => panic!("Vec3 index out of bounds: got {}", index),
}
}
}
impl AddAssign for Vec3 {
fn add_assign(&mut self, other: Self) {
*self = Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
};
}
}
impl SubAssign for Vec3 {
fn sub_assign(&mut self, other: Self) {
*self = Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
};
}
}
impl MulAssign for Vec3 {
fn mul_assign(&mut self, other: Self) {
*self = Self {
x: self.x * other.x,
y: self.y * other.y,
z: self.z * other.z,
};
}
}
impl MulAssign<f64> for Vec3 {
fn mul_assign(&mut self, t: f64) {
*self = Self {
x: self.x * t,
y: self.y * t,
z: self.z * t,
};
}
}
impl DivAssign<f64> for Vec3 {
fn div_assign(&mut self, t: f64) {
*self = Self {
x: self.x / t,
y: self.y / t,
z: self.z / t,
};
}
}
impl Add for Vec3 {
type Output = Vec3;
fn add(self, other: Self) -> Self::Output {
Vec3 {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, other: Self) -> Self::Output {
Self::Output {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
impl Mul for Vec3 {
type Output = Vec3;
fn mul(self, other: Self) -> Self::Output {
Vec3 {
x: self.x * other.x,
y: self.y * other.y,
z: self.z * other.z,
}
}
}
impl Mul<f64> for Vec3 {
type Output = Vec3;
fn mul(self, t: f64) -> Self::Output {
Vec3 {
x: self.x * t,
y: self.y * t,
z: self.z * t,
}
}
}
impl Mul<Vec3> for f64 {
type Output = Vec3;
fn mul(self, v: Self::Output) -> Self::Output {
v * self
}
}
impl Div<f64> for Vec3 {
type Output = Vec3;
fn div(self, t: f64) -> Self::Output {
Vec3 {
x: self.x / t,
y: self.y / t,
z: self.z / t,
}
}
}
impl Sum<Self> for Vec3 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Vec3::default(), |a, b| a + b)
}
}
|
#[command(usage="advancement grant <targets> everything")]
pub fn advancement_grant_targets_everything(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> everything\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement grant <targets> from <advancement>")]
pub fn advancement_grant_targets_from_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> from <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement grant <targets> only <advancement>")]
pub fn advancement_grant_targets_only_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> only <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement grant <targets> only <advancement> <criterion>")]
pub fn advancement_grant_targets_only_advancement_criterion(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation,
_criterion:StringArgumentGreedy
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> only <advancement> <criterion>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement grant <targets> through <advancement>")]
pub fn advancement_grant_targets_through_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> through <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement grant <targets> until <advancement>")]
pub fn advancement_grant_targets_until_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement grant <targets> until <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> everything")]
pub fn advancement_revoke_targets_everything(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> everything\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> from <advancement>")]
pub fn advancement_revoke_targets_from_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> from <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> only <advancement>")]
pub fn advancement_revoke_targets_only_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> only <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> only <advancement> <criterion>")]
pub fn advancement_revoke_targets_only_advancement_criterion(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation,
_criterion:StringArgumentGreedy
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> only <advancement> <criterion>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> through <advancement>")]
pub fn advancement_revoke_targets_through_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> through <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="advancement revoke <targets> until <advancement>")]
pub fn advancement_revoke_targets_until_advancement(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_advancement:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"advancement revoke <targets> until <advancement>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> base get")]
pub fn attribute_target_attribute_base_get(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> base get\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> base get <scale>")]
pub fn attribute_target_attribute_base_get_scale(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> base get <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> base set <value>")]
pub fn attribute_target_attribute_base_set_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_value:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> base set <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> get")]
pub fn attribute_target_attribute_get(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> get\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> get <scale>")]
pub fn attribute_target_attribute_get_scale(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> get <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier add <uuid> <name> <value> add")]
pub fn attribute_target_attribute_modifier_add_uuid_name_value_add(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid,
_name:StringArgumentPhrase,
_value:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier add <uuid> <name> <value> add\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier add <uuid> <name> <value> multiply")]
pub fn attribute_target_attribute_modifier_add_uuid_name_value_multiply(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid,
_name:StringArgumentPhrase,
_value:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier add <uuid> <name> <value> multiply\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier add <uuid> <name> <value> multiply_base")]
pub fn attribute_target_attribute_modifier_add_uuid_name_value_multiply_base(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid,
_name:StringArgumentPhrase,
_value:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier add <uuid> <name> <value> multiply_base\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier remove <uuid>")]
pub fn attribute_target_attribute_modifier_remove_uuid(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier remove <uuid>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier value get <uuid>")]
pub fn attribute_target_attribute_modifier_value_get_uuid(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier value get <uuid>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="attribute <target> <attribute> modifier value get <uuid> <scale>")]
pub fn attribute_target_attribute_modifier_value_get_uuid_scale(
ctx: &mut CommandCtx,
_target:SingleEntities,
_attribute:ResourceLocation,
_uuid:Uuid,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"attribute <target> <attribute> modifier value get <uuid> <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="ban <targets>")]
pub fn ban_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"ban <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="ban <targets> <reason>")]
pub fn ban_targets_reason(
ctx: &mut CommandCtx,
_targets:GameProfile,
_reason:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"ban <targets> <reason>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="ban-ip <target>")]
pub fn ban_ip_target(
ctx: &mut CommandCtx,
_target:StringArgumentWord
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"ban-ip <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="ban-ip <target> <reason>")]
pub fn ban_ip_target_reason(
ctx: &mut CommandCtx,
_target:StringArgumentWord,
_reason:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"ban-ip <target> <reason>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="banlist")]
pub fn banlist(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"banlist\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="banlist ips")]
pub fn banlist_ips(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"banlist ips\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="banlist players")]
pub fn banlist_players(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"banlist players\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar add <id> <name>")]
pub fn bossbar_add_id_name(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_name:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar add <id> <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar get <id> max")]
pub fn bossbar_get_id_max(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar get <id> max\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar get <id> players")]
pub fn bossbar_get_id_players(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar get <id> players\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar get <id> value")]
pub fn bossbar_get_id_value(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar get <id> value\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar get <id> visible")]
pub fn bossbar_get_id_visible(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar get <id> visible\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar list")]
pub fn bossbar_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar remove <id>")]
pub fn bossbar_remove_id(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar remove <id>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color blue")]
pub fn bossbar_set_id_color_blue(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color blue\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color green")]
pub fn bossbar_set_id_color_green(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color green\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color pink")]
pub fn bossbar_set_id_color_pink(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color pink\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color purple")]
pub fn bossbar_set_id_color_purple(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color purple\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color red")]
pub fn bossbar_set_id_color_red(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color red\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color white")]
pub fn bossbar_set_id_color_white(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color white\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> color yellow")]
pub fn bossbar_set_id_color_yellow(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> color yellow\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> max <max>")]
pub fn bossbar_set_id_max_max(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_max:IntegerArgumentGreaterThen1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> max <max>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> name <name>")]
pub fn bossbar_set_id_name_name(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_name:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> name <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> players")]
pub fn bossbar_set_id_players(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> players\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> players <targets>")]
pub fn bossbar_set_id_players_targets(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> players <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> style notched_10")]
pub fn bossbar_set_id_style_notched_10(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> style notched_10\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> style notched_12")]
pub fn bossbar_set_id_style_notched_12(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> style notched_12\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> style notched_20")]
pub fn bossbar_set_id_style_notched_20(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> style notched_20\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> style notched_6")]
pub fn bossbar_set_id_style_notched_6(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> style notched_6\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> style progress")]
pub fn bossbar_set_id_style_progress(
ctx: &mut CommandCtx,
_id:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> style progress\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> value <value>")]
pub fn bossbar_set_id_value_value(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_value:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="bossbar set <id> visible <visible>")]
pub fn bossbar_set_id_visible_visible(
ctx: &mut CommandCtx,
_id:ResourceLocation,
_visible:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"bossbar set <id> visible <visible>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clear")]
pub fn clear(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clear\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clear <targets>")]
pub fn clear_targets(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clear <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clear <targets> <item>")]
pub fn clear_targets_item(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_item:Predicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clear <targets> <item>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clear <targets> <item> <maxCount>")]
pub fn clear_targets_item_maxCount(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_item:Predicate,
_maxCount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clear <targets> <item> <maxCount>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination>")]
pub fn clone_begin_end_destination(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> filtered <filter>")]
pub fn clone_begin_end_destination_filtered_filter(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates,
_filter:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> filtered <filter>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> filtered <filter> force")]
pub fn clone_begin_end_destination_filtered_filter_force(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates,
_filter:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> filtered <filter> force\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> filtered <filter> move")]
pub fn clone_begin_end_destination_filtered_filter_move(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates,
_filter:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> filtered <filter> move\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> filtered <filter> normal")]
pub fn clone_begin_end_destination_filtered_filter_normal(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates,
_filter:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> filtered <filter> normal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> masked")]
pub fn clone_begin_end_destination_masked(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> masked\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> masked force")]
pub fn clone_begin_end_destination_masked_force(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> masked force\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> masked move")]
pub fn clone_begin_end_destination_masked_move(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> masked move\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> masked normal")]
pub fn clone_begin_end_destination_masked_normal(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> masked normal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> replace")]
pub fn clone_begin_end_destination_replace(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> replace\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> replace force")]
pub fn clone_begin_end_destination_replace_force(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> replace force\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> replace move")]
pub fn clone_begin_end_destination_replace_move(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> replace move\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="clone <begin> <end> <destination> replace normal")]
pub fn clone_begin_end_destination_replace_normal(
ctx: &mut CommandCtx,
_begin:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"clone <begin> <end> <destination> replace normal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get block <targetPos>")]
pub fn data_get_block_targetPos(
ctx: &mut CommandCtx,
_targetPos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get block <targetPos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get block <targetPos> <path>")]
pub fn data_get_block_targetPos_path(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get block <targetPos> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get block <targetPos> <path> <scale>")]
pub fn data_get_block_targetPos_path_scale(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_path:NbtPath,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get block <targetPos> <path> <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get entity <target>")]
pub fn data_get_entity_target(
ctx: &mut CommandCtx,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get entity <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get entity <target> <path>")]
pub fn data_get_entity_target_path(
ctx: &mut CommandCtx,
_target:SingleEntities,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get entity <target> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get entity <target> <path> <scale>")]
pub fn data_get_entity_target_path_scale(
ctx: &mut CommandCtx,
_target:SingleEntities,
_path:NbtPath,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get entity <target> <path> <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get storage <target>")]
pub fn data_get_storage_target(
ctx: &mut CommandCtx,
_target:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get storage <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get storage <target> <path>")]
pub fn data_get_storage_target_path(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get storage <target> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data get storage <target> <path> <scale>")]
pub fn data_get_storage_target_path_scale(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_path:NbtPath,
_scale:DoubleArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data get storage <target> <path> <scale>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data merge block <targetPos> <nbt>")]
pub fn data_merge_block_targetPos_nbt(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_nbt:NbtCommandTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data merge block <targetPos> <nbt>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data merge entity <target> <nbt>")]
pub fn data_merge_entity_target_nbt(
ctx: &mut CommandCtx,
_target:SingleEntities,
_nbt:NbtCommandTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data merge entity <target> <nbt>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data merge storage <target> <nbt>")]
pub fn data_merge_storage_target_nbt(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_nbt:NbtCommandTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data merge storage <target> <nbt>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from block <sourcePos>")]
pub fn data_modify_block_targetPos_targetPath_append_from_block_sourcePos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from block <sourcePos> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_append_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from entity <source>")]
pub fn data_modify_block_targetPos_targetPath_append_from_entity_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from entity <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_append_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from storage <source>")]
pub fn data_modify_block_targetPos_targetPath_append_from_storage_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append from storage <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_append_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> append value <value>")]
pub fn data_modify_block_targetPos_targetPath_append_value_value(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> append value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from block <sourcePos>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_block_sourcePos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from block <sourcePos> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from entity <source>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_entity_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from entity <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from storage <source>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_storage_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> from storage <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> insert <index> value <value>")]
pub fn data_modify_block_targetPos_targetPath_insert_index_value_value(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_index:IntegerArgument,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> insert <index> value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from block <sourcePos>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_block_sourcePos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from block <sourcePos> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from entity <source>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_entity_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from entity <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from storage <source>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_storage_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge from storage <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_merge_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> merge value <value>")]
pub fn data_modify_block_targetPos_targetPath_merge_value_value(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> merge value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from block <sourcePos>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_block_sourcePos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from block <sourcePos> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from entity <source>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_entity_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from entity <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from storage <source>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_storage_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend from storage <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_prepend_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> prepend value <value>")]
pub fn data_modify_block_targetPos_targetPath_prepend_value_value(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> prepend value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from block <sourcePos>")]
pub fn data_modify_block_targetPos_targetPath_set_from_block_sourcePos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from block <sourcePos> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_set_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from entity <source>")]
pub fn data_modify_block_targetPos_targetPath_set_from_entity_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from entity <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_set_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from storage <source>")]
pub fn data_modify_block_targetPos_targetPath_set_from_storage_source(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set from storage <source> <sourcePath>")]
pub fn data_modify_block_targetPos_targetPath_set_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify block <targetPos> <targetPath> set value <value>")]
pub fn data_modify_block_targetPos_targetPath_set_value_value(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify block <targetPos> <targetPath> set value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from block <sourcePos>")]
pub fn data_modify_entity_target_targetPath_append_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from block <sourcePos> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_append_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from entity <source>")]
pub fn data_modify_entity_target_targetPath_append_from_entity_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from entity <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_append_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from storage <source>")]
pub fn data_modify_entity_target_targetPath_append_from_storage_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append from storage <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_append_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> append value <value>")]
pub fn data_modify_entity_target_targetPath_append_value_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> append value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from block <sourcePos>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from block <sourcePos> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from entity <source>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_entity_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from entity <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from storage <source>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_storage_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> from storage <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_insert_index_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> insert <index> value <value>")]
pub fn data_modify_entity_target_targetPath_insert_index_value_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_index:IntegerArgument,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> insert <index> value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from block <sourcePos>")]
pub fn data_modify_entity_target_targetPath_merge_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from block <sourcePos> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_merge_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from entity <source>")]
pub fn data_modify_entity_target_targetPath_merge_from_entity_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from entity <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_merge_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from storage <source>")]
pub fn data_modify_entity_target_targetPath_merge_from_storage_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge from storage <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_merge_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> merge value <value>")]
pub fn data_modify_entity_target_targetPath_merge_value_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> merge value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from block <sourcePos>")]
pub fn data_modify_entity_target_targetPath_prepend_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from block <sourcePos> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_prepend_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from entity <source>")]
pub fn data_modify_entity_target_targetPath_prepend_from_entity_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from entity <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_prepend_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from storage <source>")]
pub fn data_modify_entity_target_targetPath_prepend_from_storage_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend from storage <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_prepend_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> prepend value <value>")]
pub fn data_modify_entity_target_targetPath_prepend_value_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> prepend value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from block <sourcePos>")]
pub fn data_modify_entity_target_targetPath_set_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from block <sourcePos> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_set_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from entity <source>")]
pub fn data_modify_entity_target_targetPath_set_from_entity_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from entity <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_set_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from storage <source>")]
pub fn data_modify_entity_target_targetPath_set_from_storage_source(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set from storage <source> <sourcePath>")]
pub fn data_modify_entity_target_targetPath_set_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify entity <target> <targetPath> set value <value>")]
pub fn data_modify_entity_target_targetPath_set_value_value(
ctx: &mut CommandCtx,
_target:SingleEntities,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify entity <target> <targetPath> set value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from block <sourcePos>")]
pub fn data_modify_storage_target_targetPath_append_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from block <sourcePos> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_append_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from entity <source>")]
pub fn data_modify_storage_target_targetPath_append_from_entity_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from entity <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_append_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from storage <source>")]
pub fn data_modify_storage_target_targetPath_append_from_storage_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append from storage <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_append_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> append value <value>")]
pub fn data_modify_storage_target_targetPath_append_value_value(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> append value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from block <sourcePos>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from block <sourcePos> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from entity <source>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_entity_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from entity <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from storage <source>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_storage_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> from storage <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_insert_index_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> insert <index> value <value>")]
pub fn data_modify_storage_target_targetPath_insert_index_value_value(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_index:IntegerArgument,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> insert <index> value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from block <sourcePos>")]
pub fn data_modify_storage_target_targetPath_merge_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from block <sourcePos> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_merge_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from entity <source>")]
pub fn data_modify_storage_target_targetPath_merge_from_entity_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from entity <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_merge_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from storage <source>")]
pub fn data_modify_storage_target_targetPath_merge_from_storage_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge from storage <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_merge_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> merge value <value>")]
pub fn data_modify_storage_target_targetPath_merge_value_value(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> merge value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from block <sourcePos>")]
pub fn data_modify_storage_target_targetPath_prepend_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from block <sourcePos> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_prepend_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from entity <source>")]
pub fn data_modify_storage_target_targetPath_prepend_from_entity_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from entity <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_prepend_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from storage <source>")]
pub fn data_modify_storage_target_targetPath_prepend_from_storage_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend from storage <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_prepend_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> prepend value <value>")]
pub fn data_modify_storage_target_targetPath_prepend_value_value(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> prepend value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from block <sourcePos>")]
pub fn data_modify_storage_target_targetPath_set_from_block_sourcePos(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from block <sourcePos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from block <sourcePos> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_set_from_block_sourcePos_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_sourcePos:Coordinates,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from block <sourcePos> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from entity <source>")]
pub fn data_modify_storage_target_targetPath_set_from_entity_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from entity <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from entity <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_set_from_entity_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:SingleEntities,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from entity <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from storage <source>")]
pub fn data_modify_storage_target_targetPath_set_from_storage_source(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from storage <source>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set from storage <source> <sourcePath>")]
pub fn data_modify_storage_target_targetPath_set_from_storage_source_sourcePath(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_source:ResourceLocation,
_sourcePath:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set from storage <source> <sourcePath>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data modify storage <target> <targetPath> set value <value>")]
pub fn data_modify_storage_target_targetPath_set_value_value(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_targetPath:NbtPath,
_value:NbtTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data modify storage <target> <targetPath> set value <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data remove block <targetPos> <path>")]
pub fn data_remove_block_targetPos_path(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data remove block <targetPos> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data remove entity <target> <path>")]
pub fn data_remove_entity_target_path(
ctx: &mut CommandCtx,
_target:SingleEntities,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data remove entity <target> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="data remove storage <target> <path>")]
pub fn data_remove_storage_target_path(
ctx: &mut CommandCtx,
_target:ResourceLocation,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"data remove storage <target> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack disable <name>")]
pub fn datapack_disable_name(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack disable <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack enable <name>")]
pub fn datapack_enable_name(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack enable <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack enable <name> after <existing>")]
pub fn datapack_enable_name_after_existing(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase,
_existing:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack enable <name> after <existing>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack enable <name> before <existing>")]
pub fn datapack_enable_name_before_existing(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase,
_existing:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack enable <name> before <existing>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack enable <name> first")]
pub fn datapack_enable_name_first(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack enable <name> first\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack enable <name> last")]
pub fn datapack_enable_name_last(
ctx: &mut CommandCtx,
_name:StringArgumentPhrase
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack enable <name> last\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack list")]
pub fn datapack_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack list available")]
pub fn datapack_list_available(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack list available\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="datapack list enabled")]
pub fn datapack_list_enabled(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"datapack list enabled\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="debug report")]
pub fn debug_report(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"debug report\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="debug start")]
pub fn debug_start(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"debug start\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="debug stop")]
pub fn debug_stop(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"debug stop\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="defaultgamemode adventure")]
pub fn defaultgamemode_adventure(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"defaultgamemode adventure\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="defaultgamemode creative")]
pub fn defaultgamemode_creative(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"defaultgamemode creative\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="defaultgamemode spectator")]
pub fn defaultgamemode_spectator(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"defaultgamemode spectator\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="defaultgamemode survival")]
pub fn defaultgamemode_survival(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"defaultgamemode survival\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="deop <targets>")]
pub fn deop_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"deop <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="difficulty")]
pub fn difficulty(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"difficulty\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="difficulty easy")]
pub fn difficulty_easy(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"difficulty easy\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="difficulty hard")]
pub fn difficulty_hard(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"difficulty hard\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="difficulty normal")]
pub fn difficulty_normal(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"difficulty normal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="difficulty peaceful")]
pub fn difficulty_peaceful(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"difficulty peaceful\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect clear")]
pub fn effect_clear(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect clear\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect clear <targets>")]
pub fn effect_clear_targets(
ctx: &mut CommandCtx,
_targets:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect clear <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect clear <targets> <effect>")]
pub fn effect_clear_targets_effect(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_effect:MobEffect
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect clear <targets> <effect>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect give <targets> <effect>")]
pub fn effect_give_targets_effect(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_effect:MobEffect
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect give <targets> <effect>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect give <targets> <effect> <seconds>")]
pub fn effect_give_targets_effect_seconds(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_effect:MobEffect,
_seconds:IntegerArgumentBetween1And1000000
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect give <targets> <effect> <seconds>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect give <targets> <effect> <seconds> <amplifier>")]
pub fn effect_give_targets_effect_seconds_amplifier(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_effect:MobEffect,
_seconds:IntegerArgumentBetween1And1000000,
_amplifier:IntegerArgumentBetween0And255
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect give <targets> <effect> <seconds> <amplifier>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="effect give <targets> <effect> <seconds> <amplifier> <hideParticles>")]
pub fn effect_give_targets_effect_seconds_amplifier_hideParticles(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_effect:MobEffect,
_seconds:IntegerArgumentBetween1And1000000,
_amplifier:IntegerArgumentBetween0And255,
_hideParticles:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"effect give <targets> <effect> <seconds> <amplifier> <hideParticles>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="enchant <targets> <enchantment>")]
pub fn enchant_targets_enchantment(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_enchantment:Enchantment
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"enchant <targets> <enchantment>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="enchant <targets> <enchantment> <level>")]
pub fn enchant_targets_enchantment_level(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_enchantment:Enchantment,
_level:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"enchant <targets> <enchantment> <level>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if block <pos> <block>")]
pub fn execute_if_block_pos_block(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if block <pos> <block>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if blocks <start> <end> <destination> all")]
pub fn execute_if_blocks_start_end_destination_all(
ctx: &mut CommandCtx,
_start:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if blocks <start> <end> <destination> all\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if blocks <start> <end> <destination> masked")]
pub fn execute_if_blocks_start_end_destination_masked(
ctx: &mut CommandCtx,
_start:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if blocks <start> <end> <destination> masked\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if data block <sourcePos> <path>")]
pub fn execute_if_data_block_sourcePos_path(
ctx: &mut CommandCtx,
_sourcePos:Coordinates,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if data block <sourcePos> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if data entity <source> <path>")]
pub fn execute_if_data_entity_source_path(
ctx: &mut CommandCtx,
_source:SingleEntities,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if data entity <source> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if data storage <source> <path>")]
pub fn execute_if_data_storage_source_path(
ctx: &mut CommandCtx,
_source:ResourceLocation,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if data storage <source> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if entity <entities>")]
pub fn execute_if_entity_entities(
ctx: &mut CommandCtx,
_entities:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if entity <entities>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if predicate <predicate>")]
pub fn execute_if_predicate_predicate(
ctx: &mut CommandCtx,
_predicate:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if predicate <predicate>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> < <source> <sourceObjective>")]
pub fn execute_if_score_target_targetObjective_lt_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> < <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> <= <source> <sourceObjective>")]
pub fn execute_if_score_target_targetObjective_lteq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> <= <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> = <source> <sourceObjective>")]
pub fn execute_if_score_target_targetObjective_eq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> = <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> > <source> <sourceObjective>")]
pub fn execute_if_score_target_targetObjective_gt_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> > <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> >= <source> <sourceObjective>")]
pub fn execute_if_score_target_targetObjective_gteq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> >= <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute if score <target> <targetObjective> matches <range>")]
pub fn execute_if_score_target_targetObjective_matches_range(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_range:IntRage
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute if score <target> <targetObjective> matches <range>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless block <pos> <block>")]
pub fn execute_unless_block_pos_block(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless block <pos> <block>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless blocks <start> <end> <destination> all")]
pub fn execute_unless_blocks_start_end_destination_all(
ctx: &mut CommandCtx,
_start:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless blocks <start> <end> <destination> all\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless blocks <start> <end> <destination> masked")]
pub fn execute_unless_blocks_start_end_destination_masked(
ctx: &mut CommandCtx,
_start:Coordinates,
_end:Coordinates,
_destination:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless blocks <start> <end> <destination> masked\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless data block <sourcePos> <path>")]
pub fn execute_unless_data_block_sourcePos_path(
ctx: &mut CommandCtx,
_sourcePos:Coordinates,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless data block <sourcePos> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless data entity <source> <path>")]
pub fn execute_unless_data_entity_source_path(
ctx: &mut CommandCtx,
_source:SingleEntities,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless data entity <source> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless data storage <source> <path>")]
pub fn execute_unless_data_storage_source_path(
ctx: &mut CommandCtx,
_source:ResourceLocation,
_path:NbtPath
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless data storage <source> <path>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless entity <entities>")]
pub fn execute_unless_entity_entities(
ctx: &mut CommandCtx,
_entities:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless entity <entities>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless predicate <predicate>")]
pub fn execute_unless_predicate_predicate(
ctx: &mut CommandCtx,
_predicate:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless predicate <predicate>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> < <source> <sourceObjective>")]
pub fn execute_unless_score_target_targetObjective_lt_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> < <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> <= <source> <sourceObjective>")]
pub fn execute_unless_score_target_targetObjective_lteq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> <= <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> = <source> <sourceObjective>")]
pub fn execute_unless_score_target_targetObjective_eq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> = <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> > <source> <sourceObjective>")]
pub fn execute_unless_score_target_targetObjective_gt_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> > <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> >= <source> <sourceObjective>")]
pub fn execute_unless_score_target_targetObjective_gteq_source_sourceObjective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_source:SingleScoreHolder,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> >= <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="execute unless score <target> <targetObjective> matches <range>")]
pub fn execute_unless_score_target_targetObjective_matches_range(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_targetObjective:Objective,
_range:IntRage
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"execute unless score <target> <targetObjective> matches <range>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience add <targets> <amount>")]
pub fn experience_add_targets_amount(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience add <targets> <amount>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience add <targets> <amount> levels")]
pub fn experience_add_targets_amount_levels(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience add <targets> <amount> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience add <targets> <amount> points")]
pub fn experience_add_targets_amount_points(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience add <targets> <amount> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience query <targets> levels")]
pub fn experience_query_targets_levels(
ctx: &mut CommandCtx,
_targets:SinglePlayer
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience query <targets> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience query <targets> points")]
pub fn experience_query_targets_points(
ctx: &mut CommandCtx,
_targets:SinglePlayer
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience query <targets> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience set <targets> <amount>")]
pub fn experience_set_targets_amount(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience set <targets> <amount>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience set <targets> <amount> levels")]
pub fn experience_set_targets_amount_levels(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience set <targets> <amount> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="experience set <targets> <amount> points")]
pub fn experience_set_targets_amount_points(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"experience set <targets> <amount> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block>")]
pub fn fill_from_to_block(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> destroy")]
pub fn fill_from_to_block_destroy(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> destroy\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> hollow")]
pub fn fill_from_to_block_hollow(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> hollow\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> keep")]
pub fn fill_from_to_block_keep(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> keep\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> outline")]
pub fn fill_from_to_block_outline(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> outline\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> replace")]
pub fn fill_from_to_block_replace(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> replace\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="fill <from> <to> <block> replace <filter>")]
pub fn fill_from_to_block_replace_filter(
ctx: &mut CommandCtx,
_from:Coordinates,
_to:Coordinates,
_block:BlockState,
_filter:BlockPredicate
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"fill <from> <to> <block> replace <filter>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload add <from>")]
pub fn forceload_add_from(
ctx: &mut CommandCtx,
_from:ColumnPos
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload add <from>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload add <from> <to>")]
pub fn forceload_add_from_to(
ctx: &mut CommandCtx,
_from:ColumnPos,
_to:ColumnPos
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload add <from> <to>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload query")]
pub fn forceload_query(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload query\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload query <pos>")]
pub fn forceload_query_pos(
ctx: &mut CommandCtx,
_pos:ColumnPos
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload query <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload remove all")]
pub fn forceload_remove_all(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload remove all\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload remove <from>")]
pub fn forceload_remove_from(
ctx: &mut CommandCtx,
_from:ColumnPos
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload remove <from>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="forceload remove <from> <to>")]
pub fn forceload_remove_from_to(
ctx: &mut CommandCtx,
_from:ColumnPos,
_to:ColumnPos
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"forceload remove <from> <to>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="function <name>")]
pub fn function_name(
ctx: &mut CommandCtx,
_name:MinecraftFunction
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"function <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode adventure")]
pub fn gamemode_adventure(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode adventure\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode adventure <target>")]
pub fn gamemode_adventure_target(
ctx: &mut CommandCtx,
_target:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode adventure <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode creative")]
pub fn gamemode_creative(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode creative\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode creative <target>")]
pub fn gamemode_creative_target(
ctx: &mut CommandCtx,
_target:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode creative <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode spectator")]
pub fn gamemode_spectator(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode spectator\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode spectator <target>")]
pub fn gamemode_spectator_target(
ctx: &mut CommandCtx,
_target:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode spectator <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode survival")]
pub fn gamemode_survival(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode survival\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamemode survival <target>")]
pub fn gamemode_survival_target(
ctx: &mut CommandCtx,
_target:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamemode survival <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule announceAdvancements")]
pub fn gamerule_announceAdvancements(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule announceAdvancements\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule announceAdvancements <value>")]
pub fn gamerule_announceAdvancements_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule announceAdvancements <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule commandBlockOutput")]
pub fn gamerule_commandBlockOutput(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule commandBlockOutput\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule commandBlockOutput <value>")]
pub fn gamerule_commandBlockOutput_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule commandBlockOutput <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule disableElytraMovementCheck")]
pub fn gamerule_disableElytraMovementCheck(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule disableElytraMovementCheck\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule disableElytraMovementCheck <value>")]
pub fn gamerule_disableElytraMovementCheck_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule disableElytraMovementCheck <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule disableRaids")]
pub fn gamerule_disableRaids(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule disableRaids\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule disableRaids <value>")]
pub fn gamerule_disableRaids_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule disableRaids <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doDaylightCycle")]
pub fn gamerule_doDaylightCycle(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doDaylightCycle\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doDaylightCycle <value>")]
pub fn gamerule_doDaylightCycle_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doDaylightCycle <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doEntityDrops")]
pub fn gamerule_doEntityDrops(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doEntityDrops\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doEntityDrops <value>")]
pub fn gamerule_doEntityDrops_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doEntityDrops <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doFireTick")]
pub fn gamerule_doFireTick(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doFireTick\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doFireTick <value>")]
pub fn gamerule_doFireTick_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doFireTick <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doImmediateRespawn")]
pub fn gamerule_doImmediateRespawn(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doImmediateRespawn\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doImmediateRespawn <value>")]
pub fn gamerule_doImmediateRespawn_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doImmediateRespawn <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doInsomnia")]
pub fn gamerule_doInsomnia(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doInsomnia\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doInsomnia <value>")]
pub fn gamerule_doInsomnia_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doInsomnia <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doLimitedCrafting")]
pub fn gamerule_doLimitedCrafting(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doLimitedCrafting\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doLimitedCrafting <value>")]
pub fn gamerule_doLimitedCrafting_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doLimitedCrafting <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doMobLoot")]
pub fn gamerule_doMobLoot(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doMobLoot\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doMobLoot <value>")]
pub fn gamerule_doMobLoot_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doMobLoot <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doMobSpawning")]
pub fn gamerule_doMobSpawning(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doMobSpawning\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doMobSpawning <value>")]
pub fn gamerule_doMobSpawning_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doMobSpawning <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doPatrolSpawning")]
pub fn gamerule_doPatrolSpawning(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doPatrolSpawning\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doPatrolSpawning <value>")]
pub fn gamerule_doPatrolSpawning_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doPatrolSpawning <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doTileDrops")]
pub fn gamerule_doTileDrops(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doTileDrops\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doTileDrops <value>")]
pub fn gamerule_doTileDrops_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doTileDrops <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doTraderSpawning")]
pub fn gamerule_doTraderSpawning(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doTraderSpawning\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doTraderSpawning <value>")]
pub fn gamerule_doTraderSpawning_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doTraderSpawning <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doWeatherCycle")]
pub fn gamerule_doWeatherCycle(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doWeatherCycle\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule doWeatherCycle <value>")]
pub fn gamerule_doWeatherCycle_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule doWeatherCycle <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule drowningDamage")]
pub fn gamerule_drowningDamage(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule drowningDamage\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule drowningDamage <value>")]
pub fn gamerule_drowningDamage_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule drowningDamage <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule fallDamage")]
pub fn gamerule_fallDamage(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule fallDamage\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule fallDamage <value>")]
pub fn gamerule_fallDamage_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule fallDamage <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule fireDamage")]
pub fn gamerule_fireDamage(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule fireDamage\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule fireDamage <value>")]
pub fn gamerule_fireDamage_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule fireDamage <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule forgiveDeadPlayers")]
pub fn gamerule_forgiveDeadPlayers(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule forgiveDeadPlayers\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule forgiveDeadPlayers <value>")]
pub fn gamerule_forgiveDeadPlayers_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule forgiveDeadPlayers <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule keepInventory")]
pub fn gamerule_keepInventory(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule keepInventory\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule keepInventory <value>")]
pub fn gamerule_keepInventory_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule keepInventory <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule logAdminCommands")]
pub fn gamerule_logAdminCommands(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule logAdminCommands\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule logAdminCommands <value>")]
pub fn gamerule_logAdminCommands_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule logAdminCommands <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule maxCommandChainLength")]
pub fn gamerule_maxCommandChainLength(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule maxCommandChainLength\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule maxCommandChainLength <value>")]
pub fn gamerule_maxCommandChainLength_value(
ctx: &mut CommandCtx,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule maxCommandChainLength <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule maxEntityCramming")]
pub fn gamerule_maxEntityCramming(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule maxEntityCramming\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule maxEntityCramming <value>")]
pub fn gamerule_maxEntityCramming_value(
ctx: &mut CommandCtx,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule maxEntityCramming <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule mobGriefing")]
pub fn gamerule_mobGriefing(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule mobGriefing\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule mobGriefing <value>")]
pub fn gamerule_mobGriefing_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule mobGriefing <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule naturalRegeneration")]
pub fn gamerule_naturalRegeneration(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule naturalRegeneration\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule naturalRegeneration <value>")]
pub fn gamerule_naturalRegeneration_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule naturalRegeneration <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule randomTickSpeed")]
pub fn gamerule_randomTickSpeed(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule randomTickSpeed\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule randomTickSpeed <value>")]
pub fn gamerule_randomTickSpeed_value(
ctx: &mut CommandCtx,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule randomTickSpeed <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule reducedDebugInfo")]
pub fn gamerule_reducedDebugInfo(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule reducedDebugInfo\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule reducedDebugInfo <value>")]
pub fn gamerule_reducedDebugInfo_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule reducedDebugInfo <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule sendCommandFeedback")]
pub fn gamerule_sendCommandFeedback(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule sendCommandFeedback\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule sendCommandFeedback <value>")]
pub fn gamerule_sendCommandFeedback_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule sendCommandFeedback <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule showDeathMessages")]
pub fn gamerule_showDeathMessages(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule showDeathMessages\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule showDeathMessages <value>")]
pub fn gamerule_showDeathMessages_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule showDeathMessages <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule spawnRadius")]
pub fn gamerule_spawnRadius(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule spawnRadius\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule spawnRadius <value>")]
pub fn gamerule_spawnRadius_value(
ctx: &mut CommandCtx,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule spawnRadius <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule spectatorsGenerateChunks")]
pub fn gamerule_spectatorsGenerateChunks(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule spectatorsGenerateChunks\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule spectatorsGenerateChunks <value>")]
pub fn gamerule_spectatorsGenerateChunks_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule spectatorsGenerateChunks <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule universalAnger")]
pub fn gamerule_universalAnger(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule universalAnger\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="gamerule universalAnger <value>")]
pub fn gamerule_universalAnger_value(
ctx: &mut CommandCtx,
_value:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"gamerule universalAnger <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="give <targets> <item>")]
pub fn give_targets_item(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_item:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"give <targets> <item>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="give <targets> <item> <count>")]
pub fn give_targets_item_count(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_item:ItemStack,
_count:IntegerArgumentGreaterThen1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"give <targets> <item> <count>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="help")]
pub fn help(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"help\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="help <command>")]
pub fn help_command(
ctx: &mut CommandCtx,
_command:StringArgumentGreedy
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"help <command>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="kick <targets>")]
pub fn kick_targets(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"kick <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="kick <targets> <reason>")]
pub fn kick_targets_reason(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_reason:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"kick <targets> <reason>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="kill")]
pub fn kill(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"kill\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="kill <targets>")]
pub fn kill_targets(
ctx: &mut CommandCtx,
_targets:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"kill <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="list")]
pub fn list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="list uuids")]
pub fn list_uuids(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"list uuids\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate bastion_remnant")]
pub fn locate_bastion_remnant(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate bastion_remnant\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate buried_treasure")]
pub fn locate_buried_treasure(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate buried_treasure\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate desert_pyramid")]
pub fn locate_desert_pyramid(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate desert_pyramid\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate endcity")]
pub fn locate_endcity(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate endcity\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate fortress")]
pub fn locate_fortress(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate fortress\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate igloo")]
pub fn locate_igloo(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate igloo\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate jungle_pyramid")]
pub fn locate_jungle_pyramid(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate jungle_pyramid\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate mansion")]
pub fn locate_mansion(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate mansion\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate mineshaft")]
pub fn locate_mineshaft(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate mineshaft\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate monument")]
pub fn locate_monument(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate monument\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate nether_fossil")]
pub fn locate_nether_fossil(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate nether_fossil\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate ocean_ruin")]
pub fn locate_ocean_ruin(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate ocean_ruin\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate pillager_outpost")]
pub fn locate_pillager_outpost(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate pillager_outpost\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate ruined_portal")]
pub fn locate_ruined_portal(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate ruined_portal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate shipwreck")]
pub fn locate_shipwreck(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate shipwreck\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate stronghold")]
pub fn locate_stronghold(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate stronghold\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate swamp_hut")]
pub fn locate_swamp_hut(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate swamp_hut\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locate village")]
pub fn locate_village(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locate village\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="locatebiome <biome>")]
pub fn locatebiome_biome(
ctx: &mut CommandCtx,
_biome:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"locatebiome <biome>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> fish <loot_table> <pos>")]
pub fn loot_give_players_fish_loot_table_pos(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> fish <loot_table> <pos> mainhand")]
pub fn loot_give_players_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> fish <loot_table> <pos> offhand")]
pub fn loot_give_players_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> fish <loot_table> <pos> <tool>")]
pub fn loot_give_players_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> kill <target>")]
pub fn loot_give_players_kill_target(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> loot <loot_table>")]
pub fn loot_give_players_loot_loot_table(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> mine <pos>")]
pub fn loot_give_players_mine_pos(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> mine <pos> mainhand")]
pub fn loot_give_players_mine_pos_mainhand(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> mine <pos> offhand")]
pub fn loot_give_players_mine_pos_offhand(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot give <players> mine <pos> <tool>")]
pub fn loot_give_players_mine_pos_tool(
ctx: &mut CommandCtx,
_players:MultiplePlayers,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot give <players> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> fish <loot_table> <pos>")]
pub fn loot_insert_targetPos_fish_loot_table_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> fish <loot_table> <pos> mainhand")]
pub fn loot_insert_targetPos_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> fish <loot_table> <pos> offhand")]
pub fn loot_insert_targetPos_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> fish <loot_table> <pos> <tool>")]
pub fn loot_insert_targetPos_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> kill <target>")]
pub fn loot_insert_targetPos_kill_target(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> loot <loot_table>")]
pub fn loot_insert_targetPos_loot_loot_table(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> mine <pos>")]
pub fn loot_insert_targetPos_mine_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> mine <pos> mainhand")]
pub fn loot_insert_targetPos_mine_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> mine <pos> offhand")]
pub fn loot_insert_targetPos_mine_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot insert <targetPos> mine <pos> <tool>")]
pub fn loot_insert_targetPos_mine_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot insert <targetPos> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> fish <loot_table> <pos>")]
pub fn loot_replace_block_targetPos_slot_fish_loot_table_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> fish <loot_table> <pos> mainhand")]
pub fn loot_replace_block_targetPos_slot_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> fish <loot_table> <pos> offhand")]
pub fn loot_replace_block_targetPos_slot_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> fish <loot_table> <pos> <tool>")]
pub fn loot_replace_block_targetPos_slot_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> kill <target>")]
pub fn loot_replace_block_targetPos_slot_kill_target(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> loot <loot_table>")]
pub fn loot_replace_block_targetPos_slot_loot_loot_table(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> mine <pos>")]
pub fn loot_replace_block_targetPos_slot_mine_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> mine <pos> mainhand")]
pub fn loot_replace_block_targetPos_slot_mine_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> mine <pos> offhand")]
pub fn loot_replace_block_targetPos_slot_mine_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> mine <pos> <tool>")]
pub fn loot_replace_block_targetPos_slot_mine_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> fish <loot_table> <pos>")]
pub fn loot_replace_block_targetPos_slot_count_fish_loot_table_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> mainhand")]
pub fn loot_replace_block_targetPos_slot_count_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> offhand")]
pub fn loot_replace_block_targetPos_slot_count_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> <tool>")]
pub fn loot_replace_block_targetPos_slot_count_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> kill <target>")]
pub fn loot_replace_block_targetPos_slot_count_kill_target(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> loot <loot_table>")]
pub fn loot_replace_block_targetPos_slot_count_loot_loot_table(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> mine <pos>")]
pub fn loot_replace_block_targetPos_slot_count_mine_pos(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> mine <pos> mainhand")]
pub fn loot_replace_block_targetPos_slot_count_mine_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> mine <pos> offhand")]
pub fn loot_replace_block_targetPos_slot_count_mine_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace block <targetPos> <slot> <count> mine <pos> <tool>")]
pub fn loot_replace_block_targetPos_slot_count_mine_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Coordinates,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace block <targetPos> <slot> <count> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> fish <loot_table> <pos>")]
pub fn loot_replace_entity_entities_slot_fish_loot_table_pos(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> fish <loot_table> <pos> mainhand")]
pub fn loot_replace_entity_entities_slot_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> fish <loot_table> <pos> offhand")]
pub fn loot_replace_entity_entities_slot_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> fish <loot_table> <pos> <tool>")]
pub fn loot_replace_entity_entities_slot_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> kill <target>")]
pub fn loot_replace_entity_entities_slot_kill_target(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> loot <loot_table>")]
pub fn loot_replace_entity_entities_slot_loot_loot_table(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> mine <pos>")]
pub fn loot_replace_entity_entities_slot_mine_pos(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> mine <pos> mainhand")]
pub fn loot_replace_entity_entities_slot_mine_pos_mainhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> mine <pos> offhand")]
pub fn loot_replace_entity_entities_slot_mine_pos_offhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> mine <pos> <tool>")]
pub fn loot_replace_entity_entities_slot_mine_pos_tool(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> fish <loot_table> <pos>")]
pub fn loot_replace_entity_entities_slot_count_fish_loot_table_pos(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> fish <loot_table> <pos> mainhand")]
pub fn loot_replace_entity_entities_slot_count_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> fish <loot_table> <pos> offhand")]
pub fn loot_replace_entity_entities_slot_count_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> fish <loot_table> <pos> <tool>")]
pub fn loot_replace_entity_entities_slot_count_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> kill <target>")]
pub fn loot_replace_entity_entities_slot_count_kill_target(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> loot <loot_table>")]
pub fn loot_replace_entity_entities_slot_count_loot_loot_table(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> mine <pos>")]
pub fn loot_replace_entity_entities_slot_count_mine_pos(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> mine <pos> mainhand")]
pub fn loot_replace_entity_entities_slot_count_mine_pos_mainhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> mine <pos> offhand")]
pub fn loot_replace_entity_entities_slot_count_mine_pos_offhand(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot replace entity <entities> <slot> <count> mine <pos> <tool>")]
pub fn loot_replace_entity_entities_slot_count_mine_pos_tool(
ctx: &mut CommandCtx,
_entities:MultipleEntities,
_slot:ItemSlot,
_count:IntegerArgumentPositive,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot replace entity <entities> <slot> <count> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> fish <loot_table> <pos>")]
pub fn loot_spawn_targetPos_fish_loot_table_pos(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> fish <loot_table> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> fish <loot_table> <pos> mainhand")]
pub fn loot_spawn_targetPos_fish_loot_table_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> fish <loot_table> <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> fish <loot_table> <pos> offhand")]
pub fn loot_spawn_targetPos_fish_loot_table_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_loot_table:ResourceLocation,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> fish <loot_table> <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> fish <loot_table> <pos> <tool>")]
pub fn loot_spawn_targetPos_fish_loot_table_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_loot_table:ResourceLocation,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> fish <loot_table> <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> kill <target>")]
pub fn loot_spawn_targetPos_kill_target(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> kill <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> loot <loot_table>")]
pub fn loot_spawn_targetPos_loot_loot_table(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_loot_table:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> loot <loot_table>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> mine <pos>")]
pub fn loot_spawn_targetPos_mine_pos(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> mine <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> mine <pos> mainhand")]
pub fn loot_spawn_targetPos_mine_pos_mainhand(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> mine <pos> mainhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> mine <pos> offhand")]
pub fn loot_spawn_targetPos_mine_pos_offhand(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> mine <pos> offhand\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="loot spawn <targetPos> mine <pos> <tool>")]
pub fn loot_spawn_targetPos_mine_pos_tool(
ctx: &mut CommandCtx,
_targetPos:Vec3,
_pos:Coordinates,
_tool:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"loot spawn <targetPos> mine <pos> <tool>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="me <action>")]
pub fn me_action(
ctx: &mut CommandCtx,
_action:StringArgumentGreedy
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"me <action>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="msg <targets> <message>")]
pub fn msg_targets_message(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"msg <targets> <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="op <targets>")]
pub fn op_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"op <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="pardon <targets>")]
pub fn pardon_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"pardon <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="pardon-ip <target>")]
pub fn pardon_ip_target(
ctx: &mut CommandCtx,
_target:StringArgumentWord
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"pardon-ip <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name>")]
pub fn particle_name(
ctx: &mut CommandCtx,
_name:Particle
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos>")]
pub fn particle_name_pos(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos> <delta> <speed> <count>")]
pub fn particle_name_pos_delta_speed_count(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3,
_delta:Vec3,
_speed:FloatArgumentPositive,
_count:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos> <delta> <speed> <count>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos> <delta> <speed> <count> force")]
pub fn particle_name_pos_delta_speed_count_force(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3,
_delta:Vec3,
_speed:FloatArgumentPositive,
_count:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos> <delta> <speed> <count> force\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos> <delta> <speed> <count> force <viewers>")]
pub fn particle_name_pos_delta_speed_count_force_viewers(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3,
_delta:Vec3,
_speed:FloatArgumentPositive,
_count:IntegerArgumentPositive,
_viewers:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos> <delta> <speed> <count> force <viewers>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos> <delta> <speed> <count> normal")]
pub fn particle_name_pos_delta_speed_count_normal(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3,
_delta:Vec3,
_speed:FloatArgumentPositive,
_count:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos> <delta> <speed> <count> normal\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="particle <name> <pos> <delta> <speed> <count> normal <viewers>")]
pub fn particle_name_pos_delta_speed_count_normal_viewers(
ctx: &mut CommandCtx,
_name:Particle,
_pos:Vec3,
_delta:Vec3,
_speed:FloatArgumentPositive,
_count:IntegerArgumentPositive,
_viewers:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"particle <name> <pos> <delta> <speed> <count> normal <viewers>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> ambient <targets>")]
pub fn playsound_sound_ambient_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> ambient <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> ambient <targets> <pos>")]
pub fn playsound_sound_ambient_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> ambient <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> ambient <targets> <pos> <volume>")]
pub fn playsound_sound_ambient_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> ambient <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> ambient <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_ambient_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> ambient <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> ambient <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_ambient_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> ambient <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> block <targets>")]
pub fn playsound_sound_block_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> block <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> block <targets> <pos>")]
pub fn playsound_sound_block_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> block <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> block <targets> <pos> <volume>")]
pub fn playsound_sound_block_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> block <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> block <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_block_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> block <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> block <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_block_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> block <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> hostile <targets>")]
pub fn playsound_sound_hostile_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> hostile <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> hostile <targets> <pos>")]
pub fn playsound_sound_hostile_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> hostile <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> hostile <targets> <pos> <volume>")]
pub fn playsound_sound_hostile_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> hostile <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> hostile <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_hostile_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> hostile <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> hostile <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_hostile_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> hostile <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> master <targets>")]
pub fn playsound_sound_master_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> master <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> master <targets> <pos>")]
pub fn playsound_sound_master_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> master <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> master <targets> <pos> <volume>")]
pub fn playsound_sound_master_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> master <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> master <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_master_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> master <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> master <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_master_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> master <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> music <targets>")]
pub fn playsound_sound_music_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> music <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> music <targets> <pos>")]
pub fn playsound_sound_music_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> music <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> music <targets> <pos> <volume>")]
pub fn playsound_sound_music_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> music <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> music <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_music_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> music <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> music <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_music_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> music <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> neutral <targets>")]
pub fn playsound_sound_neutral_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> neutral <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> neutral <targets> <pos>")]
pub fn playsound_sound_neutral_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> neutral <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> neutral <targets> <pos> <volume>")]
pub fn playsound_sound_neutral_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> neutral <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> neutral <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_neutral_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> neutral <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> neutral <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_neutral_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> neutral <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> player <targets>")]
pub fn playsound_sound_player_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> player <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> player <targets> <pos>")]
pub fn playsound_sound_player_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> player <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> player <targets> <pos> <volume>")]
pub fn playsound_sound_player_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> player <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> player <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_player_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> player <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> player <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_player_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> player <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> record <targets>")]
pub fn playsound_sound_record_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> record <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> record <targets> <pos>")]
pub fn playsound_sound_record_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> record <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> record <targets> <pos> <volume>")]
pub fn playsound_sound_record_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> record <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> record <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_record_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> record <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> record <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_record_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> record <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> voice <targets>")]
pub fn playsound_sound_voice_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> voice <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> voice <targets> <pos>")]
pub fn playsound_sound_voice_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> voice <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> voice <targets> <pos> <volume>")]
pub fn playsound_sound_voice_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> voice <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> voice <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_voice_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> voice <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> voice <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_voice_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> voice <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> weather <targets>")]
pub fn playsound_sound_weather_targets(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> weather <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> weather <targets> <pos>")]
pub fn playsound_sound_weather_targets_pos(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> weather <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> weather <targets> <pos> <volume>")]
pub fn playsound_sound_weather_targets_pos_volume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> weather <targets> <pos> <volume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> weather <targets> <pos> <volume> <pitch>")]
pub fn playsound_sound_weather_targets_pos_volume_pitch(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> weather <targets> <pos> <volume> <pitch>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="playsound <sound> weather <targets> <pos> <volume> <pitch> <minVolume>")]
pub fn playsound_sound_weather_targets_pos_volume_pitch_minVolume(
ctx: &mut CommandCtx,
_sound:ResourceLocation,
_targets:MultiplePlayers,
_pos:Vec3,
_volume:FloatArgumentPositive,
_pitch:FloatArgumentBetween0And2,
_minVolume:FloatArgumentBetween0And1
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"playsound <sound> weather <targets> <pos> <volume> <pitch> <minVolume>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="publish")]
pub fn publish(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"publish\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="publish <port>")]
pub fn publish_port(
ctx: &mut CommandCtx,
_port:IntegerArgumentBetween0And65535
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"publish <port>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="recipe give <targets> *")]
pub fn recipe_give_targets_star(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"recipe give <targets> *\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="recipe give <targets> <recipe>")]
pub fn recipe_give_targets_recipe(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_recipe:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"recipe give <targets> <recipe>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="recipe take <targets> *")]
pub fn recipe_take_targets_star(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"recipe take <targets> *\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="recipe take <targets> <recipe>")]
pub fn recipe_take_targets_recipe(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_recipe:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"recipe take <targets> <recipe>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="reload")]
pub fn reload(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"reload\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="replaceitem block <pos> <slot> <item>")]
pub fn replaceitem_block_pos_slot_item(
ctx: &mut CommandCtx,
_pos:Coordinates,
_slot:ItemSlot,
_item:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"replaceitem block <pos> <slot> <item>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="replaceitem block <pos> <slot> <item> <count>")]
pub fn replaceitem_block_pos_slot_item_count(
ctx: &mut CommandCtx,
_pos:Coordinates,
_slot:ItemSlot,
_item:ItemStack,
_count:IntegerArgumentBetween1And64
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"replaceitem block <pos> <slot> <item> <count>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="replaceitem entity <targets> <slot> <item>")]
pub fn replaceitem_entity_targets_slot_item(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_slot:ItemSlot,
_item:ItemStack
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"replaceitem entity <targets> <slot> <item>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="replaceitem entity <targets> <slot> <item> <count>")]
pub fn replaceitem_entity_targets_slot_item_count(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_slot:ItemSlot,
_item:ItemStack,
_count:IntegerArgumentBetween1And64
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"replaceitem entity <targets> <slot> <item> <count>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="save-all")]
pub fn save_all(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"save-all\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="save-all flush")]
pub fn save_all_flush(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"save-all flush\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="save-off")]
pub fn save_off(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"save-off\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="save-on")]
pub fn save_on(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"save-on\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="say <message>")]
pub fn say_message(
ctx: &mut CommandCtx,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"say <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="schedule clear <function>")]
pub fn schedule_clear_function(
ctx: &mut CommandCtx,
_function:StringArgumentGreedy
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"schedule clear <function>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="schedule function <function> <time>")]
pub fn schedule_function_function_time(
ctx: &mut CommandCtx,
_function:MinecraftFunction,
_time:Time
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"schedule function <function> <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="schedule function <function> <time> append")]
pub fn schedule_function_function_time_append(
ctx: &mut CommandCtx,
_function:MinecraftFunction,
_time:Time
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"schedule function <function> <time> append\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="schedule function <function> <time> replace")]
pub fn schedule_function_function_time_replace(
ctx: &mut CommandCtx,
_function:MinecraftFunction,
_time:Time
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"schedule function <function> <time> replace\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives add <objective> <criteria>")]
pub fn scoreboard_objectives_add_objective_criteria(
ctx: &mut CommandCtx,
_objective:StringArgumentWord,
_criteria:ObjectiveCriteria
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives add <objective> <criteria>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives add <objective> <criteria> <displayName>")]
pub fn scoreboard_objectives_add_objective_criteria_displayName(
ctx: &mut CommandCtx,
_objective:StringArgumentWord,
_criteria:ObjectiveCriteria,
_displayName:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives add <objective> <criteria> <displayName>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives list")]
pub fn scoreboard_objectives_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives modify <objective> displayname <displayName>")]
pub fn scoreboard_objectives_modify_objective_displayname_displayName(
ctx: &mut CommandCtx,
_objective:Objective,
_displayName:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives modify <objective> displayname <displayName>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives modify <objective> rendertype hearts")]
pub fn scoreboard_objectives_modify_objective_rendertype_hearts(
ctx: &mut CommandCtx,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives modify <objective> rendertype hearts\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives modify <objective> rendertype integer")]
pub fn scoreboard_objectives_modify_objective_rendertype_integer(
ctx: &mut CommandCtx,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives modify <objective> rendertype integer\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives remove <objective>")]
pub fn scoreboard_objectives_remove_objective(
ctx: &mut CommandCtx,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives remove <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives setdisplay <slot>")]
pub fn scoreboard_objectives_setdisplay_slot(
ctx: &mut CommandCtx,
_slot:ScoreboardSlot
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives setdisplay <slot>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard objectives setdisplay <slot> <objective>")]
pub fn scoreboard_objectives_setdisplay_slot_objective(
ctx: &mut CommandCtx,
_slot:ScoreboardSlot,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard objectives setdisplay <slot> <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players add <targets> <objective> <score>")]
pub fn scoreboard_players_add_targets_objective_score(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_objective:Objective,
_score:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players add <targets> <objective> <score>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players enable <targets> <objective>")]
pub fn scoreboard_players_enable_targets_objective(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players enable <targets> <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players get <target> <objective>")]
pub fn scoreboard_players_get_target_objective(
ctx: &mut CommandCtx,
_target:SingleScoreHolder,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players get <target> <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players list")]
pub fn scoreboard_players_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players list <target>")]
pub fn scoreboard_players_list_target(
ctx: &mut CommandCtx,
_target:SingleScoreHolder
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players list <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players operation <targets> <targetObjective> <operation> <source> <sourceObjective>")]
pub fn scoreboard_players_operation_targets_targetObjective_operation_source_sourceObjective(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_targetObjective:Objective,
_operation:Operation,
_source:MultipleScoreHolders,
_sourceObjective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players operation <targets> <targetObjective> <operation> <source> <sourceObjective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players remove <targets> <objective> <score>")]
pub fn scoreboard_players_remove_targets_objective_score(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_objective:Objective,
_score:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players remove <targets> <objective> <score>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players reset <targets>")]
pub fn scoreboard_players_reset_targets(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players reset <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players reset <targets> <objective>")]
pub fn scoreboard_players_reset_targets_objective(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players reset <targets> <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="scoreboard players set <targets> <objective> <score>")]
pub fn scoreboard_players_set_targets_objective_score(
ctx: &mut CommandCtx,
_targets:MultipleScoreHolders,
_objective:Objective,
_score:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"scoreboard players set <targets> <objective> <score>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="seed")]
pub fn seed(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"seed\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setblock <pos> <block>")]
pub fn setblock_pos_block(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setblock <pos> <block>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setblock <pos> <block> destroy")]
pub fn setblock_pos_block_destroy(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setblock <pos> <block> destroy\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setblock <pos> <block> keep")]
pub fn setblock_pos_block_keep(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setblock <pos> <block> keep\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setblock <pos> <block> replace")]
pub fn setblock_pos_block_replace(
ctx: &mut CommandCtx,
_pos:Coordinates,
_block:BlockState
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setblock <pos> <block> replace\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setidletimeout <minutes>")]
pub fn setidletimeout_minutes(
ctx: &mut CommandCtx,
_minutes:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setidletimeout <minutes>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setworldspawn")]
pub fn setworldspawn(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setworldspawn\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="setworldspawn <pos>")]
pub fn setworldspawn_pos(
ctx: &mut CommandCtx,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"setworldspawn <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spawnpoint")]
pub fn spawnpoint(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spawnpoint\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spawnpoint <targets>")]
pub fn spawnpoint_targets(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spawnpoint <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spawnpoint <targets> <pos>")]
pub fn spawnpoint_targets_pos(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_pos:Coordinates
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spawnpoint <targets> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spectate")]
pub fn spectate(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spectate\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spectate <target>")]
pub fn spectate_target(
ctx: &mut CommandCtx,
_target:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spectate <target>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spectate <target> <player>")]
pub fn spectate_target_player(
ctx: &mut CommandCtx,
_target:SingleEntities,
_player:SinglePlayer
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spectate <target> <player>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spreadplayers <center> <spreadDistance> <maxRange> under <maxHeight> <respectTeams> <targets>")]
pub fn spreadplayers_center_spreadDistance_maxRange_under_maxHeight_respectTeams_targets(
ctx: &mut CommandCtx,
_center:Vec2,
_spreadDistance:FloatArgumentPositive,
_maxRange:FloatArgumentGreaterThen1,
_maxHeight:IntegerArgumentPositive,
_respectTeams:BoolArgument,
_targets:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spreadplayers <center> <spreadDistance> <maxRange> under <maxHeight> <respectTeams> <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="spreadplayers <center> <spreadDistance> <maxRange> <respectTeams> <targets>")]
pub fn spreadplayers_center_spreadDistance_maxRange_respectTeams_targets(
ctx: &mut CommandCtx,
_center:Vec2,
_spreadDistance:FloatArgumentPositive,
_maxRange:FloatArgumentGreaterThen1,
_respectTeams:BoolArgument,
_targets:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"spreadplayers <center> <spreadDistance> <maxRange> <respectTeams> <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stop")]
pub fn stop(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stop\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets>")]
pub fn stopsound_targets(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> * <sound>")]
pub fn stopsound_targets_star_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> * <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> ambient")]
pub fn stopsound_targets_ambient(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> ambient\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> ambient <sound>")]
pub fn stopsound_targets_ambient_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> ambient <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> block")]
pub fn stopsound_targets_block(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> block\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> block <sound>")]
pub fn stopsound_targets_block_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> block <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> hostile")]
pub fn stopsound_targets_hostile(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> hostile\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> hostile <sound>")]
pub fn stopsound_targets_hostile_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> hostile <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> master")]
pub fn stopsound_targets_master(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> master\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> master <sound>")]
pub fn stopsound_targets_master_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> master <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> music")]
pub fn stopsound_targets_music(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> music\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> music <sound>")]
pub fn stopsound_targets_music_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> music <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> neutral")]
pub fn stopsound_targets_neutral(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> neutral\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> neutral <sound>")]
pub fn stopsound_targets_neutral_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> neutral <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> player")]
pub fn stopsound_targets_player(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> player\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> player <sound>")]
pub fn stopsound_targets_player_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> player <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> record")]
pub fn stopsound_targets_record(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> record\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> record <sound>")]
pub fn stopsound_targets_record_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> record <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> voice")]
pub fn stopsound_targets_voice(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> voice\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> voice <sound>")]
pub fn stopsound_targets_voice_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> voice <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> weather")]
pub fn stopsound_targets_weather(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> weather\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="stopsound <targets> weather <sound>")]
pub fn stopsound_targets_weather_sound(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_sound:ResourceLocation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"stopsound <targets> weather <sound>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="summon <entity>")]
pub fn summon_entity(
ctx: &mut CommandCtx,
_entity:EntitySummon
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"summon <entity>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="summon <entity> <pos>")]
pub fn summon_entity_pos(
ctx: &mut CommandCtx,
_entity:EntitySummon,
_pos:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"summon <entity> <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="summon <entity> <pos> <nbt>")]
pub fn summon_entity_pos_nbt(
ctx: &mut CommandCtx,
_entity:EntitySummon,
_pos:Vec3,
_nbt:NbtCommandTag
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"summon <entity> <pos> <nbt>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tag <targets> add <name>")]
pub fn tag_targets_add_name(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_name:StringArgumentWord
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tag <targets> add <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tag <targets> list")]
pub fn tag_targets_list(
ctx: &mut CommandCtx,
_targets:MultipleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tag <targets> list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tag <targets> remove <name>")]
pub fn tag_targets_remove_name(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_name:StringArgumentWord
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tag <targets> remove <name>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team add <team>")]
pub fn team_add_team(
ctx: &mut CommandCtx,
_team:StringArgumentWord
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team add <team>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team add <team> <displayName>")]
pub fn team_add_team_displayName(
ctx: &mut CommandCtx,
_team:StringArgumentWord,
_displayName:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team add <team> <displayName>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team empty <team>")]
pub fn team_empty_team(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team empty <team>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team join <team>")]
pub fn team_join_team(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team join <team>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team join <team> <members>")]
pub fn team_join_team_members(
ctx: &mut CommandCtx,
_team:Team,
_members:MultipleScoreHolders
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team join <team> <members>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team leave <members>")]
pub fn team_leave_members(
ctx: &mut CommandCtx,
_members:MultipleScoreHolders
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team leave <members>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team list")]
pub fn team_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team list <team>")]
pub fn team_list_team(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team list <team>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> collisionRule always")]
pub fn team_modify_team_collisionRule_always(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> collisionRule always\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> collisionRule never")]
pub fn team_modify_team_collisionRule_never(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> collisionRule never\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> collisionRule pushOtherTeams")]
pub fn team_modify_team_collisionRule_pushOtherTeams(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> collisionRule pushOtherTeams\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> collisionRule pushOwnTeam")]
pub fn team_modify_team_collisionRule_pushOwnTeam(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> collisionRule pushOwnTeam\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> color <value>")]
pub fn team_modify_team_color_value(
ctx: &mut CommandCtx,
_team:Team,
_value:Color
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> color <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> deathMessageVisibility always")]
pub fn team_modify_team_deathMessageVisibility_always(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> deathMessageVisibility always\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> deathMessageVisibility hideForOtherTeams")]
pub fn team_modify_team_deathMessageVisibility_hideForOtherTeams(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> deathMessageVisibility hideForOtherTeams\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> deathMessageVisibility hideForOwnTeam")]
pub fn team_modify_team_deathMessageVisibility_hideForOwnTeam(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> deathMessageVisibility hideForOwnTeam\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> deathMessageVisibility never")]
pub fn team_modify_team_deathMessageVisibility_never(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> deathMessageVisibility never\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> displayName <displayName>")]
pub fn team_modify_team_displayName_displayName(
ctx: &mut CommandCtx,
_team:Team,
_displayName:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> displayName <displayName>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> friendlyFire <allowed>")]
pub fn team_modify_team_friendlyFire_allowed(
ctx: &mut CommandCtx,
_team:Team,
_allowed:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> friendlyFire <allowed>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> nametagVisibility always")]
pub fn team_modify_team_nametagVisibility_always(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> nametagVisibility always\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> nametagVisibility hideForOtherTeams")]
pub fn team_modify_team_nametagVisibility_hideForOtherTeams(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> nametagVisibility hideForOtherTeams\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> nametagVisibility hideForOwnTeam")]
pub fn team_modify_team_nametagVisibility_hideForOwnTeam(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> nametagVisibility hideForOwnTeam\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> nametagVisibility never")]
pub fn team_modify_team_nametagVisibility_never(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> nametagVisibility never\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> prefix <prefix>")]
pub fn team_modify_team_prefix_prefix(
ctx: &mut CommandCtx,
_team:Team,
_prefix:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> prefix <prefix>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> seeFriendlyInvisibles <allowed>")]
pub fn team_modify_team_seeFriendlyInvisibles_allowed(
ctx: &mut CommandCtx,
_team:Team,
_allowed:BoolArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> seeFriendlyInvisibles <allowed>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team modify <team> suffix <suffix>")]
pub fn team_modify_team_suffix_suffix(
ctx: &mut CommandCtx,
_team:Team,
_suffix:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team modify <team> suffix <suffix>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="team remove <team>")]
pub fn team_remove_team(
ctx: &mut CommandCtx,
_team:Team
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"team remove <team>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teammsg <message>")]
pub fn teammsg_message(
ctx: &mut CommandCtx,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teammsg <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <destination>")]
pub fn teleport_destination(
ctx: &mut CommandCtx,
_destination:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <destination>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <location>")]
pub fn teleport_location(
ctx: &mut CommandCtx,
_location:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <location>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <destination>")]
pub fn teleport_targets_destination(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_destination:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <destination>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <location>")]
pub fn teleport_targets_location(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <location>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <location> facing entity <facingEntity>")]
pub fn teleport_targets_location_facing_entity_facingEntity(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingEntity:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <location> facing entity <facingEntity>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <location> facing entity <facingEntity> <facingAnchor>")]
pub fn teleport_targets_location_facing_entity_facingEntity_facingAnchor(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingEntity:SingleEntities,
_facingAnchor:EntityAnchor
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <location> facing entity <facingEntity> <facingAnchor>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <location> facing <facingLocation>")]
pub fn teleport_targets_location_facing_facingLocation(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingLocation:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <location> facing <facingLocation>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="teleport <targets> <location> <rotation>")]
pub fn teleport_targets_location_rotation(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_rotation:Rotation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"teleport <targets> <location> <rotation>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tell <targets> <message>")]
pub fn tell_targets_message(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tell <targets> <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tellraw <targets> <message>")]
pub fn tellraw_targets_message(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_message:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tellraw <targets> <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time add <time>")]
pub fn time_add_time(
ctx: &mut CommandCtx,
_time:Time
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time add <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time query day")]
pub fn time_query_day(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time query day\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time query daytime")]
pub fn time_query_daytime(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time query daytime\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time query gametime")]
pub fn time_query_gametime(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time query gametime\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time set day")]
pub fn time_set_day(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time set day\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time set midnight")]
pub fn time_set_midnight(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time set midnight\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time set night")]
pub fn time_set_night(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time set night\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time set noon")]
pub fn time_set_noon(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time set noon\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="time set <time>")]
pub fn time_set_time(
ctx: &mut CommandCtx,
_time:Time
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"time set <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> actionbar <title>")]
pub fn title_targets_actionbar_title(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_title:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> actionbar <title>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> clear")]
pub fn title_targets_clear(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> clear\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> reset")]
pub fn title_targets_reset(
ctx: &mut CommandCtx,
_targets:MultiplePlayers
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> reset\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> subtitle <title>")]
pub fn title_targets_subtitle_title(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_title:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> subtitle <title>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> times <fadeIn> <stay> <fadeOut>")]
pub fn title_targets_times_fadeIn_stay_fadeOut(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_fadeIn:IntegerArgumentPositive,
_stay:IntegerArgumentPositive,
_fadeOut:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> times <fadeIn> <stay> <fadeOut>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="title <targets> title <title>")]
pub fn title_targets_title_title(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_title:Component
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"title <targets> title <title>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tm <message>")]
pub fn tm_message(
ctx: &mut CommandCtx,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tm <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <destination>")]
pub fn tp_destination(
ctx: &mut CommandCtx,
_destination:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <destination>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <location>")]
pub fn tp_location(
ctx: &mut CommandCtx,
_location:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <location>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <destination>")]
pub fn tp_targets_destination(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_destination:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <destination>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <location>")]
pub fn tp_targets_location(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <location>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <location> facing entity <facingEntity>")]
pub fn tp_targets_location_facing_entity_facingEntity(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingEntity:SingleEntities
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <location> facing entity <facingEntity>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <location> facing entity <facingEntity> <facingAnchor>")]
pub fn tp_targets_location_facing_entity_facingEntity_facingAnchor(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingEntity:SingleEntities,
_facingAnchor:EntityAnchor
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <location> facing entity <facingEntity> <facingAnchor>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <location> facing <facingLocation>")]
pub fn tp_targets_location_facing_facingLocation(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_facingLocation:Vec3
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <location> facing <facingLocation>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="tp <targets> <location> <rotation>")]
pub fn tp_targets_location_rotation(
ctx: &mut CommandCtx,
_targets:MultipleEntities,
_location:Vec3,
_rotation:Rotation
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"tp <targets> <location> <rotation>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="trigger <objective>")]
pub fn trigger_objective(
ctx: &mut CommandCtx,
_objective:Objective
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"trigger <objective>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="trigger <objective> add <value>")]
pub fn trigger_objective_add_value(
ctx: &mut CommandCtx,
_objective:Objective,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"trigger <objective> add <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="trigger <objective> set <value>")]
pub fn trigger_objective_set_value(
ctx: &mut CommandCtx,
_objective:Objective,
_value:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"trigger <objective> set <value>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="w <targets> <message>")]
pub fn w_targets_message(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_message:Message
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"w <targets> <message>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather clear")]
pub fn weather_clear(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather clear\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather clear <duration>")]
pub fn weather_clear_duration(
ctx: &mut CommandCtx,
_duration:IntegerArgumentBetween0And1000000
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather clear <duration>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather rain")]
pub fn weather_rain(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather rain\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather rain <duration>")]
pub fn weather_rain_duration(
ctx: &mut CommandCtx,
_duration:IntegerArgumentBetween0And1000000
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather rain <duration>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather thunder")]
pub fn weather_thunder(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather thunder\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="weather thunder <duration>")]
pub fn weather_thunder_duration(
ctx: &mut CommandCtx,
_duration:IntegerArgumentBetween0And1000000
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"weather thunder <duration>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist add <targets>")]
pub fn whitelist_add_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist add <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist list")]
pub fn whitelist_list(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist list\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist off")]
pub fn whitelist_off(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist off\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist on")]
pub fn whitelist_on(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist on\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist reload")]
pub fn whitelist_reload(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist reload\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="whitelist remove <targets>")]
pub fn whitelist_remove_targets(
ctx: &mut CommandCtx,
_targets:GameProfile
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"whitelist remove <targets>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder add <distance>")]
pub fn worldborder_add_distance(
ctx: &mut CommandCtx,
_distance:FloatArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder add <distance>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder add <distance> <time>")]
pub fn worldborder_add_distance_time(
ctx: &mut CommandCtx,
_distance:FloatArgument,
_time:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder add <distance> <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder center <pos>")]
pub fn worldborder_center_pos(
ctx: &mut CommandCtx,
_pos:Vec2
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder center <pos>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder damage amount <damagePerBlock>")]
pub fn worldborder_damage_amount_damagePerBlock(
ctx: &mut CommandCtx,
_damagePerBlock:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder damage amount <damagePerBlock>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder damage buffer <distance>")]
pub fn worldborder_damage_buffer_distance(
ctx: &mut CommandCtx,
_distance:FloatArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder damage buffer <distance>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder get")]
pub fn worldborder_get(
ctx: &mut CommandCtx,
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder get\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder set <distance>")]
pub fn worldborder_set_distance(
ctx: &mut CommandCtx,
_distance:FloatArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder set <distance>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder set <distance> <time>")]
pub fn worldborder_set_distance_time(
ctx: &mut CommandCtx,
_distance:FloatArgument,
_time:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder set <distance> <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder warning distance <distance>")]
pub fn worldborder_warning_distance_distance(
ctx: &mut CommandCtx,
_distance:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder warning distance <distance>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="worldborder warning time <time>")]
pub fn worldborder_warning_time_time(
ctx: &mut CommandCtx,
_time:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"worldborder warning time <time>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp add <targets> <amount>")]
pub fn xp_add_targets_amount(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp add <targets> <amount>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp add <targets> <amount> levels")]
pub fn xp_add_targets_amount_levels(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp add <targets> <amount> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp add <targets> <amount> points")]
pub fn xp_add_targets_amount_points(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgument
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp add <targets> <amount> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp query <targets> levels")]
pub fn xp_query_targets_levels(
ctx: &mut CommandCtx,
_targets:SinglePlayer
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp query <targets> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp query <targets> points")]
pub fn xp_query_targets_points(
ctx: &mut CommandCtx,
_targets:SinglePlayer
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp query <targets> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp set <targets> <amount>")]
pub fn xp_set_targets_amount(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp set <targets> <amount>\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp set <targets> <amount> levels")]
pub fn xp_set_targets_amount_levels(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp set <targets> <amount> levels\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
#[command(usage="xp set <targets> <amount> points")]
pub fn xp_set_targets_amount_points(
ctx: &mut CommandCtx,
_targets:MultiplePlayers,
_amount:IntegerArgumentPositive
) -> anyhow::Result<()> {
if let Some(mut sender_message_receiver) = ctx.world.try_get_mut::<MessageReceiver>(ctx.sender)
{
let return_text = Text::from("This command \"xp set <targets> <amount> points\" is not implemented in this version of feather.").gray().italic();
sender_message_receiver.send(return_text);
}
Ok(Some("".to_string()))
}
|
// 最长公共前缀
// 编写一个函数来查找字符串数组中的最长公共前缀。
//
// 如果不存在公共前缀,返回空字符串 ""。
//
// 示例 1:
//
// 输入: ["flower","flow","flight"]
// 输出: "fl"
// 示例 2:
//
// 输入: ["dog","racecar","car"]
// 输出: ""
// 解释: 输入不存在公共前缀。
// 说明:
//
// 所有输入只包含小写字母 a-z 。
use crate::string::Solution;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let (first, others) = match strs.split_first() {
None => { return "".into(); }
Some((first, others)) => (first.as_bytes(), others.iter().map(|x| x.as_bytes()).collect::<Vec<_>>()),
};
let mut i = 0;
while i < first.len() && others.iter().all(|&s| i < s.len()) {
if others.iter().all(|&s| s[i] == first[i]) { i += 1; } else { break; }
}
String::from_utf8_lossy(&first[0..i]).into()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
assert_eq!(Solution::longest_common_prefix(vec!["flower".into(), "flow".into(), "flight".into()]), "fl");
assert_eq!(Solution::longest_common_prefix(vec![]), "");
assert_eq!(Solution::longest_common_prefix(vec!["abc".into()]), "abc");
assert_eq!(Solution::longest_common_prefix(vec!["dog".into(), "racecar".into(), "car".into()]), "");
}
} |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use super::rescue::Rescue128;
use std::{cmp::Ordering, convert::TryInto};
use winterfell::{
math::{fields::f128::BaseElement, FieldElement, StarkField},
Serializable,
};
// CONSTANTS
// ================================================================================================
const MESSAGE_BITS: usize = 254;
// TYPES AND INTERFACES
// ================================================================================================
type KeyData = [BaseElement; 2];
pub struct PrivateKey {
sec_keys: Vec<KeyData>,
pub_keys: Vec<KeyData>,
pub_key_hash: PublicKey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicKey(KeyData);
pub struct Signature {
pub ones: Vec<KeyData>,
pub zeros: Vec<KeyData>,
}
// PRIVATE KEY IMPLEMENTATION
// ================================================================================================
impl PrivateKey {
/// Returns a private key generated from the specified `seed`.
pub fn from_seed(seed: [u8; 32]) -> Self {
let keys_elements = BaseElement::prng_vector(seed, MESSAGE_BITS * 2);
let mut sec_keys = Vec::with_capacity(MESSAGE_BITS);
let mut pub_keys = Vec::with_capacity(MESSAGE_BITS);
for i in (0..keys_elements.len()).step_by(2) {
let sk = [keys_elements[i], keys_elements[i + 1]];
sec_keys.push(sk);
let pk = Rescue128::digest(&sk).to_elements();
pub_keys.push(pk);
}
let pub_key_hash = hash_pub_keys(&pub_keys);
PrivateKey {
sec_keys,
pub_keys,
pub_key_hash,
}
}
/// Returns a public key corresponding to this private key.
pub fn pub_key(&self) -> PublicKey {
self.pub_key_hash
}
/// Signs the specified 'message` with this private key.
pub fn sign(&self, message: &[u8]) -> Signature {
let mut ones = Vec::new();
let mut zeros = Vec::new();
let mut n = 0;
let elements = message_to_elements(message);
for element_bits in elements.iter().map(|e| e.as_int()) {
// make sure the most significant bit is 0
assert_eq!(element_bits & (1 << 127), 0);
for i in 0..127 {
if (element_bits >> i) & 1 == 1 {
ones.push(self.sec_keys[n]);
} else {
zeros.push(self.pub_keys[n]);
}
n += 1;
}
}
Signature { ones, zeros }
}
}
// PUBLIC KEY IMPLEMENTATION
// ================================================================================================
impl PublicKey {
/// Returns true if the specified signature was generated by signing the specified message
/// with a private key corresponding to this public key.
pub fn verify(&self, message: &[u8], sig: &Signature) -> bool {
let mut n_zeros = 0;
let mut n_ones = 0;
let mut pub_keys = Vec::with_capacity(MESSAGE_BITS);
let elements = message_to_elements(message);
for element_bits in elements.iter().map(|e| e.as_int()) {
// make sure the least significant bit is 0
assert_eq!(element_bits & (1 << 127), 0);
for i in 0..127 {
if (element_bits >> i) & 1 == 1 {
if n_ones == sig.ones.len() {
return false;
}
pub_keys.push(Rescue128::digest(&sig.ones[n_ones]).to_elements());
n_ones += 1;
} else {
if n_zeros == sig.zeros.len() {
return false;
}
pub_keys.push(sig.zeros[n_zeros]);
n_zeros += 1;
}
}
}
let pub_key_hash = hash_pub_keys(&pub_keys);
*self == pub_key_hash
}
#[allow(dead_code, clippy::wrong_self_convention)]
pub fn to_bytes(&self) -> [u8; 32] {
let mut bytes = [0; 32];
bytes[..16].copy_from_slice(&self.0[0].to_bytes());
bytes[16..].copy_from_slice(&self.0[1].to_bytes());
bytes
}
#[allow(clippy::wrong_self_convention)]
pub fn to_elements(&self) -> [BaseElement; 2] {
self.0
}
}
impl Default for PublicKey {
fn default() -> Self {
PublicKey([BaseElement::ZERO; 2])
}
}
impl Ord for PublicKey {
fn cmp(&self, other: &Self) -> Ordering {
if self.0[0] == other.0[0] {
self.0[1].as_int().cmp(&other.0[1].as_int())
} else {
self.0[0].as_int().cmp(&other.0[0].as_int())
}
}
}
impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// HELPER FUNCTIONS
// ================================================================================================
pub fn message_to_elements(message: &[u8]) -> [BaseElement; 2] {
// reduce the message to a 32-byte value
let hash = *blake3::hash(message).as_bytes();
// interpret 32 bytes as two 128-bit integers
let mut m0 = u128::from_le_bytes(hash[..16].try_into().unwrap());
let mut m1 = u128::from_le_bytes(hash[16..].try_into().unwrap());
// clear the most significant bit of the first value to ensure that it fits into 127 bits
m0 = (m0 << 1) >> 1;
// do the same thing with the second value, but also clear 8 more bits to make room for
// checksum bits
m1 = (m1 << 9) >> 9;
// compute the checksum and put it into the most significant bits of the second values;
// specifically: bit 127 is zeroed out, and 8 bits of checksum should go into bits
// 119..127 thus, we just shift the checksum left by 119 bits and OR it with m1 (which
// has top 9 bits zeroed out)
let checksum = m0.count_zeros() + m1.count_zeros();
let m1 = m1 | ((checksum as u128) << 119);
[BaseElement::from(m0), BaseElement::from(m1)]
}
/// Reduces a list of public key elements to a single 32-byte value. The reduction is done
/// by breaking the list into two equal parts, and then updating hash state by taking turns
/// drawing elements from each list. For example, the final hash would be equivalent to:
/// hash(key[0] | key[127] | key[1] | key[128] | key[2] | key[129] ... )
/// This hashing methodology is implemented to simplify AIR design.
fn hash_pub_keys(keys: &[KeyData]) -> PublicKey {
let mut pub_key_hash = Rescue128::new();
pub_key_hash.update(&[BaseElement::ZERO; 4]);
for i in 0..(MESSAGE_BITS / 2) {
pub_key_hash.update(&keys[i]);
pub_key_hash.update(&keys[i + MESSAGE_BITS / 2]);
}
PublicKey(pub_key_hash.finalize().to_elements())
}
|
use std::collections::HashMap;
use thiserror::Error;
use crate::Error;
#[derive(Debug, Error)]
pub enum HandlerMapError {
#[error("request was already handled")]
AlreadyHandled,
}
impl From<HandlerMapError> for Error {
fn from(err: HandlerMapError) -> Self {
Error::aborted(err)
}
}
pub enum HandlerMap<T> {
Leaf(T),
Branch(HashMap<String, HandlerMap<T>>),
}
impl<T> Default for HandlerMap<T> {
fn default() -> Self {
Self::Branch(HashMap::new())
}
}
impl<T> HandlerMap<T> {
pub fn insert<'a>(
&mut self,
mut path: impl Iterator<Item = &'a str>,
handler: T,
) -> Result<(), Error> {
match self {
Self::Leaf(_) => Err(HandlerMapError::AlreadyHandled.into()),
Self::Branch(children) => {
if let Some(component) = path.next() {
let node = children.entry(component.to_owned()).or_default();
node.insert(path, handler)
} else if children.is_empty() {
*self = Self::Leaf(handler);
Ok(())
} else {
Err(HandlerMapError::AlreadyHandled.into())
}
}
}
}
pub fn get<'a>(&self, mut path: impl Iterator<Item = &'a str>) -> Option<&T> {
match self {
Self::Leaf(t) => Some(t),
Self::Branch(m) => {
let component = path.next()?;
m.get(component)?.get(path)
}
}
}
pub fn remove<'a>(&mut self, mut path: impl Iterator<Item = &'a str>) -> Option<T> {
match self {
Self::Leaf(_) => match std::mem::take(self) {
Self::Leaf(t) => Some(t),
_ => unreachable!(),
},
Self::Branch(map) => {
let component = path.next()?;
let next = map.get_mut(component)?;
let result = next.remove(path);
match &*next {
Self::Branch(b) if b.is_empty() => {
map.remove(component);
}
_ => (),
}
result
}
}
}
}
pub struct SubscriberMap<T> {
subscribed: Vec<T>,
children: HashMap<String, SubscriberMap<T>>,
}
impl<T> Default for SubscriberMap<T> {
fn default() -> Self {
Self {
subscribed: Vec::new(),
children: HashMap::new(),
}
}
}
impl<T> SubscriberMap<T> {
pub fn insert<'a>(&mut self, mut path: impl Iterator<Item = &'a str>, handler: T) {
if let Some(component) = path.next() {
self.children
.entry(component.to_owned())
.or_default()
.insert(path, handler);
} else {
self.subscribed.push(handler);
}
}
pub fn is_empty(&self) -> bool {
self.children.is_empty() && self.subscribed.is_empty()
}
pub fn retain<'a>(
&mut self,
mut path: impl Iterator<Item = &'a str>,
fun: &mut impl FnMut(&T) -> bool,
) {
self.subscribed.retain(|x| fun(x));
if let Some(next) = path.next() {
if let Some(y) = self.children.get_mut(next) {
y.retain(path, fun);
if y.is_empty() {
self.children.remove(next);
}
}
}
}
}
|
use std::io::Read;
use std::fs::File;
use std::collections::HashMap;
struct Trie {
children: HashMap<char, Trie>,
value: char,
}
impl Trie {
pub fn insert(&mut self, new_val: &char) -> &Trie {
let p = match self.children.get(new_val) {
Some(child) => child,
None => {
self.children.insert(new_val.clone(), Trie { children: HashMap::new(), value: new_val.clone() });
self.children.get(new_val).unwrap()
}
};
p
}
pub fn insert_word(&mut self, new_word: &str) {
let mut chars = new_word.chars();
self.insert(&chars.next().unwrap());
self.insert_word(&chars.collect::<String>())
}
}
fn main() {
let mut file = File::open("../../assets/enable1.txt").expect("file not found");
let mut strings = String::new();
file.read_to_string(&mut strings)
.expect("something went wrong");
let mut dictionary = Trie { children: HashMap::new(), value: ' ' };
strings
.split_whitespace()
.for_each(|word: &str| {
dictionary.insert_word(word)
})
// let mut input: String = String::new();
// io::stdin().read_line(&mut input)
// .expect("failed to read line");
// let input = input.trim();
//
// let mut output: String = String::new();
//
// for word in input.split_whitespace() {
// let _word = word.to_lowercase();
// let _word = _word.trim_right_matches(".");
// match dict.get(_word) {
// Some(_) => { output.push_str(word) }
// None => {
// let possible_words: Vec<String> = check_word(&_word)
// .into_iter()
// .filter(
// |ref possible_word: &String| dict.get(possible_word.as_str())
// .is_some()
// )
// .collect();
// let possible_words = possible_words
// .into_iter()
// .fold(String::new(), |mut acc, word| {
// acc.push_str(&word);
// acc.push_str(", ");
// acc
// });
// output.push('{');
// output.push_str(&possible_words);
// output.pop();
// output.pop();
// output.push('}')
// }
// }
// output.push(' ')
// }
// output.pop();
//
// println!("{:?}", output);
}
|
use board;
use moves;
use movement;
use square;
use time;
const hash_map_size : usize = 0x100000;
const inf : i32 = 100000;
static mut time_up : bool = false;
// TODO src https://chessprogramming.wikispaces.com/Simplified+evaluation+function
const black_pawn_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 50, 50, 50, 50, 50, 50, 50, 50, 0,
0, 10, 10, 20, 30, 30, 20, 10, 10, 0,
0, 5, 5, 10, 25, 25, 10, 5, 5, 0,
0, 0, 0, 0, 20, 20, 0, 0, 0, 0,
0, 5, -5,-10, 0, 0, -10, -5, 5, 0,
0, 5, 10, 10,-20,-20, 10, 10, 5, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const white_pawn_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 5, 10, 10,-20,-20, 10, 10, 5, 0,
0, 5, -5,-10, 0, 0, -10, -5, 5, 0,
0, 0, 0, 0, 20, 20, 0, 0, 0, 0,
0, 5, 5, 10, 25, 25, 10, 5, 5, 0,
0, 10, 10, 20, 30, 30, 20, 10, 10, 0,
0, 50, 50, 50, 50, 50, 50, 50, 50, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const black_knight_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -50,-40,-30,-30,-30,-30,-40,-50, 0,
0, -40,-20, 0, 0, 0, 0,-20,-40, 0,
0, -30, 0, 10, 15, 15, 10, 0,-30, 0,
0, -30, 5, 15, 20, 20, 15, 5,-30, 0,
0, -30, 0, 15, 20, 20, 15, 0,-30, 0,
0, -30, 5, 10, 15, 15, 10, 5,-30, 0,
0, -40,-20, 0, 5, 5, 0,-20,-40, 0,
0, -50,-40,-30,-30,-30,-30,-40,-50, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const white_knight_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -50,-40,-30,-30,-30,-30,-40,-50, 0,
0, -40,-20, 0, 5, 5, 0,-20,-40, 0,
0, -30, 5, 10, 15, 15, 10, 5,-30, 0,
0, -30, 0, 15, 20, 20, 15, 0,-30, 0,
0, -30, 5, 15, 20, 20, 15, 5,-30, 0,
0, -30, 0, 10, 15, 15, 10, 0,-30, 0,
0, -40,-20, 0, 0, 0, 0,-20,-40, 0,
0, -50,-40,-30,-30,-30,-30,-40,-50, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const black_bishop_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -20,-10,-10,-10,-10,-10,-10,-20, 0,
0, -10, 0, 0, 0, 0, 0, 0,-10, 0,
0, -10, 0, 5, 10, 10, 5, 0,-10, 0,
0, -10, 5, 5, 10, 10, 5, 5,-10, 0,
0, -10, 0, 10, 10, 10, 10, 0,-10, 0,
0, -10, 10, 10, 10, 10, 10, 10,-10, 0,
0, -10, 5, 0, 0, 0, 0, 5,-10, 0,
0, -20,-10,-10,-10,-10,-10,-10,-20, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const white_bishop_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -20,-10,-10,-10,-10,-10,-10,-20, 0,
0, -10, 5, 0, 0, 0, 0, 5,-10, 0,
0, -10, 10, 10, 10, 10, 10, 10,-10, 0,
0, -10, 0, 10, 10, 10, 10, 0,-10, 0,
0, -10, 5, 5, 10, 10, 5, 5,-10, 0,
0, -10, 0, 5, 10, 10, 5, 0,-10, 0,
0, -10, 0, 0, 0, 0, 0, 0,-10, 0,
0, -20,-10,-10,-10,-10,-10,-10,-20, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const black_rook_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 5, 10, 10, 10, 10, 10, 10, 5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, 0, 0, 0, 5, 5, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const white_rook_piece_square : [i32; 120] =
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 5, 5, 0, 0, 0, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, -5, 0, 0, 0, 0, 0, 0, -5, 0,
0, 5, 10, 10, 10, 10, 10, 10, 5, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
pub struct transposition {
pub hash: u64,
pub move_: u32
}
impl transposition {
fn empty() -> transposition {
transposition {
hash: 0,
move_: 0
}
}
}
pub struct transposition_table {
pub entries: Vec<transposition>
}
impl transposition_table {
pub fn new() -> transposition_table {
let mut vector = Vec::new();
for _ in 0..hash_map_size {
vector.push(transposition::empty());
}
transposition_table{
entries: vector
}
}
}
pub fn store_transposition(move_ : u32, cboard : &mut board::chessboard) {
let x = cboard.zobrist % hash_map_size as u64;
let i = x as usize;
cboard.transposition_table.entries[i].hash = cboard.zobrist;
cboard.transposition_table.entries[i].move_ = move_;
}
pub fn find_transposition(cboard: &board::chessboard) -> u32 {
let x = cboard.zobrist % hash_map_size as u64;
let i = x as usize;
// TODO collisions here should be astronomically rare
// but is this really the case?
if cboard.zobrist == cboard.transposition_table.entries[i].hash {
cboard.transposition_table.entries[i].move_
} else {
0
}
}
pub fn repetition (cboard : &board::chessboard) -> bool{
for x in (cboard.depth - cboard.fifty as u16) as usize..cboard.depth as usize - 1 {
if cboard.zobrist == cboard.past[x].zobrist {
return true
}
}
false
}
fn evaluate (cboard: &board::chessboard) -> i32 {
// raw score = white - black
let material_balance = cboard.score[0] - cboard.score[1];
let mut score = material_balance;
for x in 0..cboard.piece_count[board::piece::P as usize] as usize{
let loc = cboard.piece_list[board::piece::P as usize][x];
score += white_pawn_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::p as usize] as usize{
let loc = cboard.piece_list[board::piece::p as usize][x];
score -= black_pawn_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::N as usize] as usize {
let loc = cboard.piece_list[board::piece::N as usize][x];
score += white_knight_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::n as usize] as usize {
let loc = cboard.piece_list[board::piece::n as usize][x];
score -= black_knight_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::B as usize] as usize {
let loc = cboard.piece_list[board::piece::B as usize][x];
score += white_bishop_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::b as usize] as usize {
let loc = cboard.piece_list[board::piece::b as usize][x];
score -= black_bishop_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::R as usize] as usize {
let loc = cboard.piece_list[board::piece::R as usize][x];
score += white_rook_piece_square[loc as usize];
}
for x in 0..cboard.piece_count[board::piece::r as usize] as usize {
let loc = cboard.piece_list[board::piece::r as usize][x];
score -= black_rook_piece_square[loc as usize];
}
if cboard.side == board::white {
score
} else {
-score
}
}
pub fn start(cboard: &mut board::chessboard, depth_target: u8, think_time:i64) {
use std::u8;
let mut best : u32 = 0;
let mut score = 0;
cboard.ply = 0;
let mut end = time::SteadyTime::now() + time::Duration::milliseconds((think_time/30) - 75);
let mut target = depth_target;
unsafe { time_up = false; }
if think_time == 0 {
end = time::SteadyTime::now() + time::Duration::weeks(1);
}
if depth_target == 0 {
target = u8::MAX - 1;
}
let mut bestmove = moves::_move{container: 0, score:0};
unsafe {
for depth in 1..target+1 {
let mut node : u64 = 0;
score = alpha_beta(-inf, inf, depth, cboard, &mut node, end);
if node != 0 && !time_up {
print!("info depth {} score cp {} nodes {}", depth, score, node);
print_pv(cboard, depth as usize);
println!();
bestmove = moves::_move{container: find_transposition(cboard), score:0};
}
}
}
print!("bestmove ");
let move_ = moves::to_AN(&bestmove);
for m in &move_[0..5] {
print!("{}", m);
}
println!();
}
fn alpha_beta(alpha: i32, beta: i32, depth: u8, cboard: &mut board::chessboard, node : &mut u64, end : time::SteadyTime) -> i32 {
if depth == 0 {
return quiescence(alpha, beta, cboard);
}
if *node % 10000 == 0 && time::SteadyTime::now() > end {
unsafe { time_up = true; }
return 0
}
unsafe {
if time_up {
return 0
}
}
let mut new_alpha = alpha;
let stale_alpha = alpha;
let mut illegal = true;
let mut move_ = 0;
let mut score = -inf;
if (repetition(cboard) || cboard.fifty > 99) && cboard.ply > 0 {
return 0
}
if cboard.depth == board::max_game_length as u16 - 1 {
return evaluate(cboard)
}
let mut move_list : moves::movelist = moves::movelist::new();
moves::generator(&mut move_list, cboard);
let pv = moves::_move{container: find_transposition(cboard), score: 0};
if pv.container != 0 {
for b in 0..move_list.count as usize {
if move_list.all[b].container == pv.container {
move_list.all[b].score = 40000;
break
}
}
}
for index in 0..move_list.count as usize {
optimize_mvv_lva(index, &mut move_list);
if !movement::make(&move_list.all[index], cboard) {
continue
}
*node += 1;
if illegal {
illegal = false;
}
score = -alpha_beta(-beta, -new_alpha, depth - 1, cboard, node, end);
movement::undo(cboard);
if score > new_alpha {
if score >= beta {
return beta
}
new_alpha = score;
move_ = move_list.all[index].container;
}
}
if illegal {
// checkmate
if cboard.side == board::white {
return if square::attacked(cboard.piece_list[board::piece::K as usize][0], board::black, cboard) {
-board::piece_value[1] as i32 + cboard.ply as i32
} else {
// stalemate
0
};
} else {
return if square::attacked(cboard.piece_list[board::piece::k as usize][0], board::white, cboard) {
-board::piece_value[1] as i32 + cboard.ply as i32
} else {
// stalemate
0
};
}
}
if stale_alpha != new_alpha {
store_transposition(move_, cboard);
}
new_alpha
}
fn quiescence(alpha: i32, beta: i32, cboard: &mut board::chessboard) -> i32 {
if (repetition(cboard) || cboard.fifty > 99) && cboard.ply > 0 {
return 0
}
if cboard.depth == board::max_game_length as u16 - 1 {
return evaluate(cboard)
}
let eval = evaluate(cboard);
let mut new_alpha = alpha;
let stale_alpha = alpha;
let mut illegal = true;
let mut _move = 0;
let mut score = -inf;
if eval >= beta {
return beta
}
if eval > alpha {
new_alpha = eval;
}
let mut move_list : moves::movelist = moves::movelist::new();
moves::generator(&mut move_list, cboard);
for index in 0..move_list.count as usize {
if moves::capture(&move_list.all[index]) != 0 {
optimize_mvv_lva(index, &mut move_list);
if !movement::make(&move_list.all[index], cboard) {
continue
}
if illegal {
illegal = false;
}
score = -quiescence(-beta, -new_alpha, cboard);
movement::undo(cboard);
if score > new_alpha {
if score >= beta {
return beta
}
new_alpha = score;
_move = move_list.all[index].container;
}
}
}
new_alpha
}
fn optimize_mvv_lva(index : usize, list : &mut moves::movelist) {
let mut max_score = list.all[index].score;
let mut max_index = index;
let old_move = moves::_move{
container: list.all[index].container,
score: list.all[index].score};
for x in index .. list.count as usize {
if list.all[x].score > max_score {
max_score = list.all[x].score;
max_index = x;
}
}
list.all[index].score = list.all[max_index].score;
list.all[index].container = list.all[max_index].container;
list.all[max_index] = old_move;
}
fn print_pv(cboard : &mut board::chessboard, depth : usize) {
print!(" pv ");
let mut var_depth = depth;
for y in 0..depth {
if find_transposition(cboard) != 0 {
let bestmove = moves::_move{container: find_transposition(cboard), score:0};
let move_ = moves::to_AN(&bestmove);
for m in &move_[0..5] {
print!("{}", m);
}
print!(" ");
movement::make(&bestmove, cboard);
} else {
var_depth = y;
break
}
}
for _ in 0..var_depth {
movement::undo(cboard);
}
}
|
extern crate rand;
extern crate amcl_wrapper;
pub mod musig;
|
//! Helper for enabling Alfred workflows to upgrade themselves periodically (Alfred 3+)
//!
//! Using this module, the workflow author can make Alfred check for latest releases
//! ([`try_update_ready()`] or [`update_ready()`]) from a remote server within adjustable intervals
//! (default is 24 hrs).
//!
//! Additionally they can ask Alfred to download the new release to its cache folder for further
//! action: [`download_latest()`].
//!
//! For convenience, an associated method [`Updater::gh()`] is available to check
//! for workflows hosted on `github.com`.
//!
//! However, it's possible to check with other servers as long as the [`Releaser`] trait is
//! implemented for the desired remote service.
//! See [`Updater::new()`] documentation if you are hosting your workflow
//! on a non `github.com` service.
//!
//! ## Notes:
//! - The `github.com` hosted repository should have release items following `github`'s process.
//! This can be done by tagging a commit and then manually building a release where you
//! attach/upload `YourWorkflow.alfredworkflow` to the release page.
//! You can easily create `YourWorkflow.alfredworkflow` file by using the [export feature] of
//! Alfred in its preferences window.
//!
//! - The tag should follow all of the [semantic versioning] rules.
//! The only exception to those rules is that you can prepend your
//! semantic version tag with ASCII letter `v`: `v0.3.1` or `0.3.1`
//!
//! # Note to workflow authors
//! - Depending on network quality, checking if an update is available may take a long time.
//! This module may spawn a worker thread so that the check does not block the main flow of your plugin.
//! However given the limitations of Alfred's plugin architecture, the worker thread cannot outlive
//! your plugin's executable. This means that you either have to wait/block for the worker thread,
//! or if it is taking longer than a desirable time, you will have to abandon it.
//! See the example for more details.
//! - Workflow authors should make sure that _released_ workflow bundles have
//! their version set in [Alfred's preferences window]. However, this module provides
//! [`set_version()`] to set the version during runtime.
//!
//! [`Releaser`]: trait.Releaser.html
//! [`Updater`]: struct.Updater.html
//! [`update_ready()`]: struct.Updater.html#method.update_ready
//! [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
//! [`download_latest()`]: struct.Updater.html#method.download_latest
//! [`Updater::gh()`]: struct.Updater.html#method.gh
//! [`Updater::new()`]: struct.Updater.html#method.new
//! [semantic versioning]: https://semver.org
//! [export feature]: https://www.alfredapp.com/help/workflows/advanced/sharing-workflows/
//! [Alfred's preferences window]: https://www.alfredapp.com/help/workflows/advanced/variables/
//! [`set_version()`]: struct.Updater.html#method.set_version
//! [`set_interval()`]: struct.Updater.html#method.set_interval
//!
//! # Example
//!
//! Create an updater for a workflow hosted on `github.com/spamwax/alfred-pinboard-rs`.
//! By default, it will check for new releases every 24 hours.
//! To change the interval, use [`set_interval()`] method.
//!
//! ```rust,no_run
//! # use anyhow::Result;
//! extern crate alfred;
//!
//! // This crate
//! extern crate alfred_rs;
//!
//! use alfred::{Item, ItemBuilder, json};
//! use alfred_rs::Updater;
//!
//! # use std::io;
//! # fn produce_items_for_user_to_see<'a>() -> Vec<Item<'a>> {
//! # Vec::new()
//! # }
//! # fn do_some_other_stuff() {}
//! // Our workflow's main 'runner' function
//! fn run<'a>() -> Result<Vec<Item<'a>>> {
//! let updater = Updater::gh("spamwax/alfred-pinboard-rs")?;
//!
//! // Start the process for getting latest release info
//! updater.init().expect("cannot initialize updater");
//!
//! // We'll do some other work that's related to our workflow:
//! do_some_other_stuff();
//! let mut items: Vec<Item> = produce_items_for_user_to_see();
//!
//! // We can now check if update is ready using two methods:
//! // 1- Block and wait until we receive results from worker thread
//! // It's a good practice to only wait for worker for a limited time so
//! // our workflow doesn't become unresponsive (not shown here)
//! let update_status = updater.update_ready();
//!
//! // 2- Or without blocking, check if the worker thread sent the results.
//! // If the worker thread is still busy, we'll get an `Err`
//! let update_status = updater.try_update_ready();
//!
//! if let Ok(is_ready) = update_status { // Comm. with worker was successful
//! // Check for new update and add an item to 'items'
//! if is_ready {
//! let update_item = ItemBuilder::new(
//! "New version is available!"
//! ).into_item();
//! // Add a new item to previous list of Items
//! items.push(update_item);
//! }
//! } else {
//! /* worker thread wasn't successful */
//! }
//! Ok(items)
//! }
//!
//! fn main() {
//! // Fetch the items and show them.
//! if let Ok(ref items) = run() {
//! json::write_items(io::stdout(), items);
//! }
//! }
//! ```
//!
//! An *issue* with above example can be when user is on a poor network or server is unresponsive.
//! In this case, the above snippet will try to call server every time workflow is invoked
//! by Alfred until the operation succeeds.
use super::{anyhow, bail, chrono, env_logger, semver, serde_json, url, Result};
use crate::env;
use chrono::prelude::*;
use chrono::Duration;
use reqwest;
use semver::Version;
use std::cell::RefCell;
use std::env as StdEnv;
use std::fs::{remove_file, File};
use std::io::BufWriter;
use std::path::PathBuf;
use std::sync::mpsc::Receiver;
use url::Url;
mod imp;
mod releaser;
#[cfg(test)]
mod tests;
/// Default update check interval duration (24 hrs). To change the interval use the
/// [`set_interval()`] method.
///
/// [`set_interval()`]: struct.Updater.html#method.set_interval
pub const UPDATE_INTERVAL: i64 = 24 * 60 * 60;
pub use self::releaser::GithubReleaser;
pub use self::releaser::Releaser;
/// Struct to check for & download the latest release of workflow from a remote server.
pub struct Updater<T>
where
T: Releaser,
{
state: imp::UpdaterState,
releaser: RefCell<T>,
}
impl Updater<GithubReleaser> {
/// Create an `Updater` object that will interface with a `github` repository.
///
/// The `repo_name` should be in `user_name/repository_name` form. See the
/// [module level documentation](./index.html) for full example and description.
///
/// ```rust
/// # extern crate alfred_rs;
/// use alfred_rs::Updater;
///
/// # use std::env;
/// # fn main() {
/// # env::set_var("alfred_workflow_uid", "abcdef");
/// # env::set_var("alfred_workflow_data", env::temp_dir());
/// # env::set_var("alfred_workflow_cache", env::temp_dir());
/// # env::set_var("alfred_workflow_version", "0.0.0");
/// let updater = Updater::gh("spamwax/alfred-pinboard-rs").expect("cannot initiate Updater");
/// # }
/// ```
///
/// This only creates an `Updater` without performing any network operations.
/// To check availability of a new release, launch and check for updates by
/// using [`init()`] and [`update_ready()`] or [`try_update_ready()`] methods.
///
/// To download an available release use [`download_latest()`] method afterwards.
///
/// # Errors
/// Error will happen during calling this method if:
/// - `Updater` state cannot be read/written during instantiation, or
/// - The workflow version cannot be parsed as semantic version compatible identifier.
///
/// [`init()`]: struct.Updater.html#method.init
/// [`update_ready()`]: struct.Updater.html#method.update_ready
/// [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
/// [`download_latest()`]: struct.Updater.html#method.download_latest
pub fn gh<S>(repo_name: S) -> Result<Self>
where
S: Into<String>,
{
let releaser = GithubReleaser::new(repo_name);
Self::load_or_new(releaser)
}
}
impl<T> Updater<T>
where
T: Releaser + Send + 'static,
{
/// Create an `Updater` object that will interface with a remote repository for updating operations.
///
/// `repo_name` is an arbitrary tag/identifier associated with the remote repository.
///
/// How the `Updater` interacts with the remote server should be implemented using the [`Releaser`]
/// trait. This crate provides a default implementation for interacting with
/// `github.com` repositories, see [`gh()`] and [`GithubReleaser`].
///
/// # Example
///
/// ```rust,no_run
/// # extern crate alfred_rs;
/// # extern crate semver;
/// # use anyhow::Result;
/// # extern crate url;
///
/// use url::Url;
/// use semver::Version;
///
/// use alfred_rs::Updater;
/// use alfred_rs::updater::Releaser;
/// # use std::env;
/// # fn main() {
///
/// #[derive(Clone)]
/// struct MyPrivateHost {/* inner */};
///
/// // You need to actually implement the trait, following is just a mock.
/// impl Releaser for MyPrivateHost {
/// type SemVersion = Version;
/// type DownloadLink = Url;
///
/// fn new<S: Into<String>>(project_id: S) -> Self {
/// MyPrivateHost {}
/// }
///
/// fn fetch_latest_release(&self) -> Result<(Version, Url)> {
/// let version = Version::new(1, 0, 12);
/// let url = Url::parse("https://ci.remote.cc/release/latest")?;
/// Ok((version, url))
/// }
/// }
///
/// let updater: Updater<MyPrivateHost> =
/// Updater::new("my_hidden_proj").expect("cannot initiate Updater");
/// # }
/// ```
///
/// This only creates an `Updater` without performing any network operations.
/// To check availability of a new release, launch and check for updates by
/// using [`init()`] and [`update_ready()`] or [`try_update_ready()`] methods.
///
/// To check availability of a new release use [`update_ready()`] method.
///
/// To download an available release use [`download_latest()`] method afterwards.
///
/// # Errors
/// Error will happen during calling this method if:
/// - `Updater` state cannot be read/written during instantiation, or
/// - The workflow version cannot be parsed as a semantic version compatible identifier.
///
/// [`init()`]: struct.Updater.html#method.init
/// [`update_ready()`]: struct.Updater.html#method.update_ready
/// [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
/// [`download_latest()`]: struct.Updater.html#method.download_latest
/// [`Releaser`]: trait.Releaser.html
/// [`GithubReleaser`]: struct.GithubReleaser.html
/// [`gh()`]: struct.Updater.html#method.gh
pub fn new<S>(repo_name: S) -> Result<Updater<T>>
where
S: Into<String>,
{
let releaser = Releaser::new(repo_name);
Self::load_or_new(releaser)
}
/// Initializes `Updater` to fetch latest release information.
///
/// - If it has been more than [`UPDATE_INTERVAL`] seconds (see [`set_interval()`]) since last check,
/// the method will spawn a worker thread.
/// In the background, the spawned thread will attempt to make a network call to fetch metadata of releases
/// *only if* `UPDATE_INTERVAL` seconds has passed since the last network call.
///
/// - All calls, which happen before the `UPDATE_INTERVAL` seconds, will initialize the `Updater`
/// by using a local cache to report metadata about a release.
///
/// For `Updater`s talking to `github.com`, the worker thread will only fetch a small
/// metadata information to extract the version of the latest release.
///
/// To check on status of worker thread and to get latest release status, use either of
/// [`update_ready()`] or [`try_update_ready()`] methods.
///
/// # Example
///
/// ```rust,no_run
/// # extern crate alfred_rs;
/// # use anyhow::Result;
/// # use alfred_rs::Updater;
/// # use std::env;
/// # fn do_some_other_stuff() {}
/// # fn test_async() -> Result<()> {
/// let updater = Updater::gh("spamwax/alfred-pinboard-rs")?;
///
/// let rx = updater.init().expect("Error in starting updater.");
///
/// // We'll do some other work that's related to our workflow while waiting
/// do_some_other_stuff();
///
/// // We can now check if update is ready using two methods:
/// // 1- Block and wait until we receive results or errors
/// let update_status = updater.update_ready();
///
/// // 2- Or without blocking, check if the worker thread sent the results.
/// // If the worker thread is still busy, we'll get an `Err`
/// let update_status = updater.try_update_ready();
///
/// if let Ok(is_ready) = update_status {
/// // Everything went ok:
/// // No error happened during operation of worker thread
/// // and we received release info
/// if is_ready {
/// // there is an update available.
/// }
/// } else {
/// /* either the worker thread wasn't successful or we couldn't get its results */
/// }
/// # Ok(())
/// # }
/// # fn main() {
/// # test_async();
/// # }
/// ```
///
/// # Errors
/// Followings can cause the method return an error:
/// - A worker thread cannot be spawned
/// - Alfred environment variable error
/// - File IO error
///
/// [`set_interval()`]: struct.Updater.html#method.set_interval
/// [`update_ready()`]: struct.Updater.html#method.update_ready
/// [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
/// [`UPDATE_INTERVAL`]: constant.UPDATE_INTERVAL.html
#[allow(clippy::missing_panics_doc)]
pub fn init(&self) -> Result<()> {
use self::imp::LATEST_UPDATE_INFO_CACHE_FN_ASYNC;
use std::sync::mpsc;
let _ = env_logger::try_init();
debug!("entering init");
// file for status of last update check
let p = Self::build_data_fn()?.with_file_name(LATEST_UPDATE_INFO_CACHE_FN_ASYNC);
let (tx, rx) = mpsc::channel();
if self.last_check().is_none() {
self.set_last_check(Utc::now());
self.save()?;
// This send is always successful
tx.send(Ok(None)).unwrap();
debug!(" last check was set to now()");
} else if self.due_to_check() {
// it's time to talk to remote server
debug!(" past UPDATE_INTERVAL, calling start_releaser_worker");
self.start_releaser_worker(tx, p)?;
} else {
debug!(" not past UPDATE_INTERVAL yet, calling read_last_check_status");
let status = Self::read_last_check_status(&p)
.map(|last_check| {
last_check.and_then(|info| {
debug!(" read last_check_status: {:?}", info);
if self.current_version() < info.version() {
Some(info)
} else {
None
}
})
})
.or(Ok(None));
debug!(" status: {:?}", status);
tx.send(status).unwrap();
}
*self.state.borrow_worker_mut() = Some(imp::MPSCState::new(rx));
debug!("successfully set the state of release worker");
Ok(())
}
/// Checks if a new update is available by waiting for the background thread to finish
/// fetching release info (blocking).
///
/// In practice, this method will block if it has been more than [`UPDATE_INTERVAL`] seconds
/// since last check. In any other instance the updater will return the update status
/// that was cached since last check.
///
/// This method will wait for worker thread (spawned by calling [`init()`]) to deliver release
/// information from remote server.
/// Upon successful retrieval, this method will compare release information to the current
/// vertion of the workflow. The remote repository should tag each release according to semantic
/// version scheme for this to work.
///
/// You should use this method after calling `init()`, preferably after your workflow is done with other tasks
/// and now wants to get information about the latest release.
///
/// # Note
///
/// - Since this method may block the current thread until a response is received from remote server,
/// workflow authors should consider scenarios where network connection is poor and the block can
/// take a long time (>1 second), and devise their workflow around it. An alternative to
/// this method is the non-blocking [`try_update_ready()`].
/// - The *very first* call to this method will always return false since it is assumed that
/// user has just downloaded and installed the workflow.
///
/// # Example
///
/// ```no_run
/// # extern crate alfred_rs;
/// # use anyhow::Result;
/// use alfred_rs::Updater;
///
/// # use std::io;
/// # fn main() {
/// let updater =
/// Updater::gh("spamwax/alfred-pinboard-rs").expect("cannot initiate Updater");
/// updater.init().expect("cannot start the worker thread");
///
/// // Perform other workflow related tasks...
///
/// assert_eq!(true, updater.update_ready().expect("cannot get update information"));
///
/// # }
/// ```
///
/// # Errors
/// Error will be returned :
/// - If worker thread has been interrupted
/// - If [`init()`] method has not been called successfully before this method
/// - If worker could not communicate with server
/// - If any file error or Alfred environment variable error happens
///
/// [`init()`]: struct.Updater.html#method.init
/// [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
/// [`UPDATE_INTERVAL`]: constant.UPDATE_INTERVAL.html
pub fn update_ready(&self) -> Result<bool> {
if self.state.borrow_worker().is_none() {
bail!("update_ready_sync is deprecated. use init()");
}
self.update_ready_async(false)
}
/// Try to get release info from background worker and see if a new update is available (non-blocking).
///
/// This method will attempt to receive release information from worker thread
/// (spawned by calling [`init()`]). Upon successful retrieval, this method will compare
/// release information to the current vertion of the workflow.
/// The remote repository should tag each release according to semantic version scheme
/// for this to work.
///
/// If communication with worker thread is not successful or if the worker thread could not
/// fetch release information, this method will return an error.
///
/// You should use this method after calling `init()`, preferably after your workflow is done with other tasks
/// and now wants to get information about the latest release.
///
/// # Note
///
/// - To wait for the worker thread to deliver its release information you can use the blocking
/// [`update_ready()`] method.
/// - The *very first* call to this method will always return false since it is assumed that
/// user has just downloaded and installed the workflow.
///
/// # Example
///
/// ```no_run
/// extern crate alfred_rs;
/// # use anyhow::Result;
///
/// use alfred_rs::Updater;
///
/// # use std::io;
///
/// # fn do_some_other_stuff() {}
///
/// fn main() {
/// let updater =
/// Updater::gh("spamwax/alfred-pinboard-rs").expect("cannot initiate Updater");
/// updater.init().expect("cannot start the worker thread");
///
/// // Perform other workflow related tasks...
/// do_some_other_stuff();
///
/// assert_eq!(true, updater.try_update_ready().expect("cannot get update information"));
///
/// // Execution of program will immediately follow to here since this method is non-blocking.
///
/// }
/// ```
///
/// # Errors
/// Error will be returned :
/// - If worker thread is not ready to send information or it has been interrupted
/// - If [`init()`] method has not been called successfully before this method
/// - If worker could not communicate with server
/// - If any file error or Alfred environment variable error happens
///
/// [`init()`]: struct.Updater.html#method.init
/// [`update_ready()`]: struct.Updater.html#method.update_ready
pub fn try_update_ready(&self) -> Result<bool> {
if self.state.borrow_worker().is_none() {
bail!("update_ready_sync is deprecated. use init()");
}
self.update_ready_async(true)
}
/// Set workflow's version to `version`.
///
/// Content of `version` needs to follow semantic versioning.
///
/// This method is provided so workflow authors can set the version from within the Rust code.
///
/// # Example
///
/// ```rust
/// # extern crate alfred_rs;
/// # use anyhow::Result;
/// # use alfred_rs::Updater;
/// # use std::env;
/// # fn ex_set_version() -> Result<()> {
/// # env::set_var("alfred_workflow_uid", "abcdef");
/// # env::set_var("alfred_workflow_data", env::temp_dir());
/// # env::set_var("alfred_workflow_version", "0.0.0");
/// let mut updater = Updater::gh("spamwax/alfred-pinboard-rs")?;
/// updater.set_version("0.23.3");
/// # Ok(())
/// # }
///
/// # fn main() {
/// # ex_set_version();
/// # }
/// ```
/// An alternative (recommended) way of setting version is through [Alfred's preferences window].
///
/// [Alfred's preferences window]: https://www.alfredapp.com/help/workflows/advanced/variables/
///
/// # Panics
/// The method will panic if the passed value `version` cannot be parsed as a semantic version compatible string.
pub fn set_version<S: AsRef<str>>(&mut self, version: S) {
let v = Version::parse(version.as_ref())
.expect("version should follow semantic version rules.");
self.state.set_version(v);
StdEnv::set_var("alfred_workflow_version", version.as_ref());
}
/// Set the interval between checks for a newer release (in seconds)
///
/// [Default value][`UPDATE_INTERVAL`] is 86,400 seconds (24 hrs).
///
/// # Example
/// Set interval to be 7 days
///
/// ```rust
/// # extern crate alfred_rs;
/// # use alfred_rs::Updater;
/// # use std::env;
/// # fn main() {
/// # env::set_var("alfred_workflow_uid", "abcdef");
/// # env::set_var("alfred_workflow_data", env::temp_dir());
/// # env::set_var("alfred_workflow_cache", env::temp_dir());
/// # env::set_var("alfred_workflow_version", "0.0.0");
/// let mut updater =
/// Updater::gh("spamwax/alfred-pinboard-rs").expect("cannot initiate Updater");
/// updater.set_interval(7 * 24 * 60 * 60);
/// # }
/// ```
/// [`UPDATE_INTERVAL`]: constant.UPDATE_INTERVAL.html
pub fn set_interval(&mut self, tick: i64) {
self.set_update_interval(tick);
}
/// Check if it is time to ask remote server for latest updates.
///
/// It returns `true` if it has been more than [`UPDATE_INTERVAL`] seconds since we last
/// checked with server (i.e. ran [`update_ready()`]), otherwise returns false.
///
/// [`update_ready()`]: struct.Updater.html#method.update_ready
///
/// # Example
///
/// ```rust,no_run
/// # extern crate alfred_rs;
/// # use anyhow::Result;
/// # use alfred_rs::Updater;
/// # fn run() -> Result<()> {
/// let mut updater = Updater::gh("spamwax/alfred-pinboard-rs")?;
///
/// // Assuming it is has been UPDATE_INTERVAL seconds since last time we ran the
/// // `update_ready()` and there actually exists a new release:
/// assert_eq!(true, updater.due_to_check());
/// # Ok(())
/// # }
/// # fn main() {
/// # run();
/// # }
/// ```
///
/// [`UPDATE_INTERVAL`]: constant.UPDATE_INTERVAL.html
pub fn due_to_check(&self) -> bool {
self.last_check().map_or(true, |dt| {
debug!("last check: {}", dt);
Utc::now().signed_duration_since(dt) > Duration::seconds(self.update_interval())
})
}
/// Method to download and save the latest release into workflow's cache dir.
///
/// If the download and save operations are both successful, it returns name of file in which the
/// downloaded Alfred workflow bundle is saved.
///
/// The downloaded workflow will be saved in dedicated cache folder of the workflow, and it
/// will be always renamed to `latest_release_WORKFLOW-NAME.alfredworkflow`
///
/// To install the downloaded release, your workflow needs to somehow open the saved file.
///
/// Within shell, it can be installed by issuing something like:
/// ```bash
/// open -b com.runningwithcrayons.Alfred latest_release_WORKFLOW-NAME.alfredworkflow
/// ```
///
/// Or you can add "Run script" object to your workflow and use environment variables set by
/// Alfred to automatically open the downloaded release:
/// ```bash
/// open -b com.runningwithcrayons.Alfred "$alfred_workflow_cache/latest_release_$alfred_workflow_name.alfredworkflow"
/// ```
///
/// # Note
///
/// The method may take longer than other Alfred-based actions to complete. Workflow authors using this crate
/// should implement strategies to prevent unpleasant long blocks of user's typical work flow.
///
/// One option to initiate the download and upgrade process is to invoke your executable with a
/// different argument. The following snippet can be tied to a dedicated Alfred **Hotkey**
/// or **Script Filter** so that it is only executed when user explicitly asks for it:
///
/// # Example
///
/// ```rust,no_run
/// # extern crate alfred;
/// # extern crate alfred_rs;
/// # use anyhow::Result;
/// # use std::io;
/// use alfred_rs::Updater;
/// use alfred::{ItemBuilder, json};
///
/// # fn main() {
/// # let updater =
/// # Updater::gh("spamwax/alfred-pinboard-rs").expect("cannot initiate Updater");
/// # let cmd_line_download_flag = true;
/// if cmd_line_download_flag && updater.update_ready().unwrap() {
/// match updater.download_latest() {
/// Ok(downloaded_fn) => {
/// json::write_items(io::stdout(), &[
/// ItemBuilder::new("New version of workflow is available!")
/// .subtitle("Click to upgrade!")
/// .arg(downloaded_fn.to_str().unwrap())
/// .variable("update_ready", "yes")
/// .valid(true)
/// .into_item()
/// ]);
/// },
/// Err(e) => {
/// // Show an error message to user or log it.
/// }
/// }
/// }
/// # else {
/// # }
/// # }
/// ```
///
/// For the above example to automatically work, you then need to connect the output of the script
/// to an **Open File** action so that Alfred can install/upgrade the new version.
///
/// As suggested in above example, you can add an Alfred variable to the item so that your workflow
/// can use it for further processing.
///
/// # Errors
/// Downloading latest workflow can fail if network error, file error or Alfred environment variable
/// errors happen, or if [`Releaser`] cannot produce a usable download url.
///
/// [`Releaser`]: trait.Releaser.html
pub fn download_latest(&self) -> Result<PathBuf> {
let url = self
.state
.download_url()
.ok_or_else(|| anyhow!("no release info avail yet"))?;
let client = reqwest::blocking::Client::new();
client
.get(url)
.send()?
.error_for_status()
.map_err(Into::into)
.and_then(|mut resp| {
// Get workflow's dedicated cache folder & build a filename
let workflow_name = env::workflow_name()
.unwrap_or_else(|| "WhyUNoNameYourOwnWorkflow".to_string())
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect::<String>();
let latest_release_downloaded_fn = env::workflow_cache()
.ok_or_else(|| {
anyhow!(
"missing env variable for cache dir. forgot to set workflow bundle id?",
)
})
.map(|mut cache_dir| {
cache_dir
.push(["latest_release_", &workflow_name, ".alfredworkflow"].concat());
cache_dir
})?;
// Save the file
File::create(&latest_release_downloaded_fn)
.map_err(Into::into)
.and_then(|fp| {
let mut buf_writer = BufWriter::with_capacity(0x10_0000, fp);
resp.copy_to(&mut buf_writer)?;
Ok(())
})
.map_err(|e: anyhow::Error| {
let _r = remove_file(&latest_release_downloaded_fn);
e
})?;
Ok(latest_release_downloaded_fn)
})
}
/// Returns the version for the latest downloadable workflow from [`Releaser`].
/// `None` is returned if no release info has yet been fetched from server.
///
/// # Note
/// This method does not perform any network or disk IO. It merely returns the cached
/// version info based on last successful communication with the remote server.
/// So it is possible the method will return a version different than server's version if:
/// - It's been less than [`UPDATE_INTERVAL`] seconds since last check, or
/// - Worker thread is busy checking and you called this method before it finishes.
///
/// [`Releaser`]: trait.Releaser.html
/// [`UPDATE_INTERVAL`]: constant.UPDATE_INTERVAL.html
/// [`update_ready()`]: struct.Updater.html#method.update_ready
/// [`try_update_ready()`]: struct.Updater.html#method.try_update_ready
pub fn latest_avail_version(&self) -> Option<Version> {
self.state.latest_avail_version()
}
/// Get workflow's current version
pub fn current_version(&self) -> &Version {
self.state.current_version()
}
}
|
//! Module providing an implementation of the [HtsGet] trait using a [Storage].
//!
use std::sync::Arc;
use async_trait::async_trait;
use tokio::io::AsyncRead;
use tracing::debug;
use tracing::instrument;
use htsget_config::resolver::{ResolveResponse, StorageResolver};
use htsget_config::storage::local::LocalStorage as ConfigLocalStorage;
#[cfg(feature = "s3-storage")]
use htsget_config::storage::s3::S3Storage;
use crate::htsget::search::Search;
#[cfg(feature = "s3-storage")]
use crate::storage::aws::AwsS3Storage;
use crate::storage::local::LocalStorage;
use crate::Resolver;
use crate::{
htsget::bam_search::BamSearch,
htsget::bcf_search::BcfSearch,
htsget::cram_search::CramSearch,
htsget::vcf_search::VcfSearch,
htsget::{HtsGet, Query, Response, Result},
storage::Storage,
};
use crate::{Format, HtsGetError};
/// Implementation of the [HtsGet] trait using a [Storage].
#[derive(Debug, Clone)]
pub struct HtsGetFromStorage<S> {
storage_ref: Arc<S>,
}
#[async_trait]
impl HtsGet for Vec<Resolver> {
async fn search(&self, query: Query) -> Result<Response> {
self.as_slice().search(query).await
}
}
#[async_trait]
impl HtsGet for &[Resolver] {
async fn search(&self, mut query: Query) -> Result<Response> {
self
.resolve_request::<HtsGetFromStorage<()>>(&mut query)
.await
.ok_or_else(|| HtsGetError::not_found("failed to match query with storage"))?
}
}
#[async_trait]
impl<S, R> HtsGet for HtsGetFromStorage<S>
where
R: AsyncRead + Send + Sync + Unpin,
S: Storage<Streamable = R> + Sync + Send + 'static,
{
#[instrument(level = "debug", skip(self))]
async fn search(&self, query: Query) -> Result<Response> {
debug!(format = ?query.format(), ?query, "searching {:?}, with query {:?}", query.format(), query);
match query.format() {
Format::Bam => BamSearch::new(self.storage()).search(query).await,
Format::Cram => CramSearch::new(self.storage()).search(query).await,
Format::Vcf => VcfSearch::new(self.storage()).search(query).await,
Format::Bcf => BcfSearch::new(self.storage()).search(query).await,
}
}
}
#[async_trait]
impl<S> ResolveResponse for HtsGetFromStorage<S> {
async fn from_local(local_storage: &ConfigLocalStorage, query: &Query) -> Result<Response> {
let local_storage = local_storage.clone();
let path = local_storage.local_path().to_string();
let searcher = HtsGetFromStorage::new(LocalStorage::new(path, local_storage)?);
searcher.search(query.clone()).await
}
#[cfg(feature = "s3-storage")]
async fn from_s3_storage(s3_storage: &S3Storage, query: &Query) -> Result<Response> {
let searcher = HtsGetFromStorage::new(
AwsS3Storage::new_with_default_config(
s3_storage.bucket().to_string(),
s3_storage.clone().endpoint(),
)
.await,
);
searcher.search(query.clone()).await
}
}
impl<S> HtsGetFromStorage<S> {
pub fn new(storage: S) -> Self {
Self {
storage_ref: Arc::new(storage),
}
}
pub fn storage(&self) -> Arc<S> {
Arc::clone(&self.storage_ref)
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::fs;
#[cfg(feature = "s3-storage")]
use std::fs::create_dir;
use std::future::Future;
use std::path::{Path, PathBuf};
use http::uri::Authority;
use tempfile::TempDir;
use htsget_config::storage;
use htsget_config::types::Scheme::Http;
use htsget_test::util::expected_bgzf_eof_data_url;
use crate::htsget::bam_search::tests::{
expected_url as bam_expected_url, with_local_storage as with_bam_local_storage,
};
use crate::htsget::vcf_search::tests::{
expected_url as vcf_expected_url, with_local_storage as with_vcf_local_storage,
};
#[cfg(feature = "s3-storage")]
use crate::storage::aws::tests::with_aws_s3_storage_fn;
use crate::{Headers, Url};
use super::*;
#[tokio::test]
async fn search_bam() {
with_bam_local_storage(|storage| async move {
let htsget = HtsGetFromStorage::new(Arc::try_unwrap(storage).unwrap());
let query = Query::new("htsnexus_test_NA12878", Format::Bam);
let response = htsget.search(query).await;
println!("{response:#?}");
let expected_response = Ok(Response::new(
Format::Bam,
vec![
Url::new(bam_expected_url())
.with_headers(Headers::default().with_header("Range", "bytes=0-2596770")),
Url::new(expected_bgzf_eof_data_url()),
],
));
assert_eq!(response, expected_response)
})
.await;
}
#[tokio::test]
async fn search_vcf() {
with_vcf_local_storage(|storage| async move {
let htsget = HtsGetFromStorage::new(Arc::try_unwrap(storage).unwrap());
let filename = "spec-v4.3";
let query = Query::new(filename, Format::Vcf);
let response = htsget.search(query).await;
println!("{response:#?}");
assert_eq!(response, expected_vcf_response(filename));
})
.await;
}
#[tokio::test]
async fn from_local_storage() {
with_config_local_storage(
|_, local_storage| async move {
let filename = "spec-v4.3";
let query = Query::new(filename, Format::Vcf);
let response = HtsGetFromStorage::<()>::from_local(&local_storage, &query).await;
assert_eq!(response, expected_vcf_response(filename));
},
"data/vcf",
&[],
)
.await;
}
#[tokio::test]
async fn search_resolvers() {
with_config_local_storage(
|_, local_storage| async {
let resolvers = vec![Resolver::new(
storage::Storage::Local { local_storage },
".*",
"$0",
Default::default(),
)
.unwrap()];
let filename = "spec-v4.3";
let query = Query::new(filename, Format::Vcf);
let response = resolvers.search(query).await;
assert_eq!(response, expected_vcf_response(filename));
},
"data/vcf",
&[],
)
.await;
}
fn expected_vcf_response(filename: &str) -> Result<Response> {
Ok(Response::new(
Format::Vcf,
vec![
Url::new(vcf_expected_url(filename))
.with_headers(Headers::default().with_header("Range", "bytes=0-822")),
Url::new(expected_bgzf_eof_data_url()),
],
))
}
async fn copy_files(from_path: &str, to_path: &Path, file_names: &[&str]) -> PathBuf {
let mut base_path = std::env::current_dir()
.unwrap()
.parent()
.unwrap()
.join(from_path);
for file_name in file_names {
fs::copy(base_path.join(file_name), to_path.join(file_name)).unwrap();
}
if !file_names.is_empty() {
base_path = PathBuf::from(to_path);
}
base_path
}
async fn with_config_local_storage<F, Fut>(test: F, path: &str, file_names: &[&str])
where
F: FnOnce(PathBuf, ConfigLocalStorage) -> Fut,
Fut: Future<Output = ()>,
{
let tmp_dir = TempDir::new().unwrap();
let base_path = copy_files(path, tmp_dir.path(), file_names).await;
println!("{:#?}", base_path);
test(
base_path.clone(),
ConfigLocalStorage::new(
Http,
Authority::from_static("127.0.0.1:8081"),
base_path.to_str().unwrap().to_string(),
"/data".to_string(),
),
)
.await
}
pub(crate) async fn with_local_storage_fn<F, Fut>(test: F, path: &str, file_names: &[&str])
where
F: FnOnce(Arc<LocalStorage<ConfigLocalStorage>>) -> Fut,
Fut: Future<Output = ()>,
{
with_config_local_storage(
|base_path, local_storage| async {
test(Arc::new(
LocalStorage::new(base_path, local_storage).unwrap(),
))
.await
},
path,
file_names,
)
.await;
}
#[cfg(feature = "s3-storage")]
pub(crate) async fn with_aws_storage_fn<F, Fut>(test: F, path: &str, file_names: &[&str])
where
F: FnOnce(Arc<AwsS3Storage>) -> Fut,
Fut: Future<Output = ()>,
{
let tmp_dir = TempDir::new().unwrap();
let to_path = tmp_dir.into_path().join("folder");
create_dir(&to_path).unwrap();
let base_path = copy_files(path, &to_path, file_names).await;
with_aws_s3_storage_fn(test, "folder".to_string(), base_path.parent().unwrap()).await;
}
}
|
extern crate capnp;
extern crate capnpc;
extern crate capnp_rpc;
extern crate protos;
use std::thread;
use protos::service_capnp::person_service as PersonService;
use capnp_rpc::capability::{InitRequest, LocalClient, WaitForContent};
use capnp_rpc::ez_rpc::{EzRpcClient};
fn main() {
let mut rpc_client = EzRpcClient::new("localhost:8080").unwrap();
let person_client: PersonService::Client = rpc_client.get_main();
{
let mut request = person_client.get_person_request();
let builder = request.init();
let mut promise = request.send();
let response = promise.wait().unwrap();
let person = response.get_person();
assert!(person.is_ok());
let name: &str = person.unwrap().get_name().unwrap();
assert_eq!(name, "Larry");
}
{
let mut request2 = person_client.make_person_request();
let mut builder2 = request2.init();
builder2.set_name("Bill");
let mut promise2 = request2.send();
let response2 = promise2.wait().unwrap();
let person2 = response2.get_person();
assert!(person2.is_ok());
let name2: &str = person2.unwrap().get_name().unwrap();
assert_eq!(name2, "Bill");
}
println!("{}", "OK");
}
|
use crate::helpers;
use crate::prelude::*;
use crate::runtime;
use crate::types::TransferFileMeta;
use serde_json::json;
use std::net::IpAddr;
use std::sync::Arc;
use tokio::fs::OpenOptions;
use tokio::net::{TcpListener, TcpStream};
pub fn start_server(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let config = cx.argument::<JsObject>(0)?;
let port = config.number(&mut cx, "port")?;
let receive_files_dir = config.string(&mut cx, "receiveFilesDir")?;
let on_start = config.callback(&mut cx, "onStart")?;
let on_receive_file_start = config.callback(&mut cx, "onReceiveFileStart")?;
let on_receive_file_progress = config.callback(&mut cx, "onReceiveFileProgress")?;
let on_receive_file_complete = config.callback(&mut cx, "onReceiveFileComplete")?;
let on_receive_file_error = config.callback(&mut cx, "onReceiveFileError")?;
let on_server_error = config.callback(&mut cx, "onServerError")?;
runtime::spawn(async move {
let result = spawn_tcp_server(
port as u16,
Arc::new(receive_files_dir),
on_start,
on_receive_file_start,
on_receive_file_progress,
on_receive_file_complete,
on_receive_file_error,
)
.await;
if let Err(err) = result {
// It means server is shutdown for some reason.
on_server_error.emit(move |cx| vec![cx.string(err.to_string()).upcast()])
}
});
Ok(cx.undefined())
}
async fn spawn_tcp_server(
port: u16,
receive_files_dir: Arc<String>,
on_start: EventHandler,
on_receive_file_start: EventHandler,
on_receive_file_progress: EventHandler,
on_receive_file_complete: EventHandler,
on_receive_file_error: EventHandler,
) -> crate::Result<()> {
let mut server = TcpListener::bind((IpAddr::from([0, 0, 0, 0]), port))
.await
.context(format!("Failed to bind the server to port: {}", port))?;
on_start.emit(move |_| vec![]);
while let Some(socket) = server.next().await {
let socket = socket.context("Failed to accept new connection")?;
let ref_id = Arc::new(helpers::gen_uuid());
let receive_files_dir = receive_files_dir.clone();
let on_receive_file_start = on_receive_file_start.clone();
let on_receive_file_progress = on_receive_file_progress.clone();
let on_receive_file_complete = on_receive_file_complete.clone();
let on_receive_file_error = on_receive_file_error.clone();
tokio::spawn(async move {
let result = handle_socket(
ref_id.clone(),
receive_files_dir,
socket,
on_receive_file_start,
on_receive_file_progress,
on_receive_file_complete,
)
.await;
if let Err(err) = result {
println!("{}", err);
on_receive_file_error
.emit(move |cx| vec![cx.string(ref_id.as_str()).upcast(), cx.string(err.to_string()).upcast()])
}
});
}
Ok(())
}
async fn handle_socket(
ref_id: Arc<String>,
receive_files_dir: Arc<String>,
mut socket: TcpStream,
on_receive_file_start: EventHandler,
on_receive_file_progress: EventHandler,
on_receive_file_complete: EventHandler,
) -> crate::Result<()> {
let peer_addr = socket
.peer_addr()
.context("Failed to get peer remote address while receiving file")?;
let transfer_meta = socket
.read_json::<TransferFileMeta>()
.await
.context("Failed to read transfer-meta json")?;
let cloned_ref_id = ref_id.clone();
let from_meta = json!({
"ip": peer_addr.ip().to_string(),
"port": peer_addr.port()
});
let file_mata = json!({
"name": transfer_meta.name.as_str(),
"size": transfer_meta.size
});
on_receive_file_start.emit(move |cx| {
vec![
cx.string(cloned_ref_id.as_str()).upcast(),
neon_serde::to_value(cx, &from_meta).unwrap(),
neon_serde::to_value(cx, &file_mata).unwrap(),
]
});
let output_file_path =
helpers::generate_file_path_with_available_name(receive_files_dir.as_str(), transfer_meta.name.as_str())
.context("Failed to generate a new file path for the receiving file")?;
let mut out_file = OpenOptions::new()
.write(true)
.create(true)
.open(output_file_path.as_path())
.await
.context("Failed to create a output file for the receiving file")?;
helpers::pipe(&mut socket, &mut out_file, |progress| {
let cloned_ref_id = ref_id.clone();
on_receive_file_progress.emit(move |cx| {
vec![
cx.string(cloned_ref_id.as_str()).upcast(),
cx.number(progress as f64).upcast(),
]
});
})
.await
.context("Failed to pipe socket data to the output file")?;
let cloned_ref_id = ref_id.clone();
on_receive_file_complete.emit(move |cx| {
vec![
cx.string(cloned_ref_id.as_str()).upcast(),
cx.string(output_file_path.to_str().unwrap()).upcast(),
]
});
Ok(())
}
|
//! Helper facilities for calculating content digests and signing data
use crate::error::Error;
use std::fmt;
/// The supported algorithms for creating a digest of content
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DigestAlgorithm {
Sha256,
}
/// The supported algorithms for signing payloads
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SigningAlgorithm {
RsaSha256,
}
/// The supported key formats
pub enum Key<'a> {
/// Unencrypted PKCS#8 RSA private key. See [ring](https://briansmith.org/rustdoc/ring/signature/struct.RsaKeyPair.html#method.from_pkcs8)
/// for more information
Pkcs8(&'a [u8]),
/// Uncencrypted RSA private key that isn't wrapped in PKCS#8. See [ring](https://briansmith.org/rustdoc/ring/signature/struct.RsaKeyPair.html#method.from_der)
/// for more information
Der(&'a [u8]),
/// See [ring](https://briansmith.org/rustdoc/ring/hmac/index.html) for more information.
Hmac(&'a [u8]),
}
impl<'a> fmt::Debug for Key<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Key::Pkcs8(_) => "pkcs8",
Key::Der(_) => "der",
Key::Hmac(_) => "hmac",
};
write!(f, "{}", name)
}
}
/// Used to calculate a digest of payloads with a specific algorithm
pub trait DigestCalulator {
/// Calculate a digest of a block of data, the algorithm determines the size
/// of the slice used for returning the digest
fn digest(&self, algorithm: DigestAlgorithm, data: &[u8], output_digest: &mut [u8]);
}
/// Used to sign a block of data
pub trait Signer {
/// Sign a block of data with the specified algorith, and a private key
fn sign(
&self,
algorithm: SigningAlgorithm,
key: Key<'_>,
data: &[u8],
) -> Result<Vec<u8>, Error>;
}
/// Internal type use to grab the pieces of the service account we need for signing
#[derive(Deserialize, Debug, Clone)]
struct ServiceAccountInfo {
/// The private key we use to sign
private_key: String,
/// The unique id used as the issuer of the JWT claim
client_email: String,
}
/// Provides the details needed for signing a URL
pub trait KeyProvider {
/// The actual key used to sign the URL
fn key(&self) -> Key<'_>;
/// The identifier for the key author, in GCP this is the email
/// address of the service account
fn authorizer(&self) -> &str;
}
/// A [GCP service account](https://cloud.google.com/iam/docs/creating-managing-service-account-keys),
/// used as a `KeyProvider` when signing URLs.
pub struct ServiceAccount {
key: Vec<u8>,
email: String,
}
impl ServiceAccount {
/// Attempts to load a service account from a JSON file
pub fn load_json_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
let file_content = std::fs::read(path)?;
Self::load_json(file_content)
}
/// Attempts to load a service account from a JSON byte slice
pub fn load_json<B: AsRef<[u8]>>(json_data: B) -> Result<Self, Error> {
let info: ServiceAccountInfo = serde_json::from_slice(json_data.as_ref())?;
let key_string = info
.private_key
.split("-----")
.nth(2)
.ok_or_else(|| Error::KeyRejected("invalid key format".to_owned()))?;
// Strip out all of the newlines
let key_string = key_string.split_whitespace().fold(
String::with_capacity(key_string.len()),
|mut s, line| {
s.push_str(line);
s
},
);
use base64::Engine;
let key_bytes = base64::engine::general_purpose::STANDARD
.decode(key_string.as_bytes())
.map_err(Error::Base64Decode)?;
Ok(Self {
key: key_bytes,
email: info.client_email,
})
}
}
impl KeyProvider for ServiceAccount {
fn key(&self) -> Key<'_> {
Key::Pkcs8(&self.key)
}
fn authorizer(&self) -> &str {
&self.email
}
}
/// Implements `DigestCalculator` via [`ring`](https://briansmith.org/rustdoc/ring/digest/index.html)
#[cfg(feature = "signing")]
pub struct RingDigest;
#[cfg(feature = "signing")]
impl DigestCalulator for RingDigest {
fn digest(&self, algorithm: DigestAlgorithm, data: &[u8], output_digest: &mut [u8]) {
use ring::digest;
match algorithm {
DigestAlgorithm::Sha256 => {
assert_eq!(
output_digest.len(),
32,
"output digest has invalid length for Sha256"
);
let digest = digest::digest(&digest::SHA256, data);
output_digest.copy_from_slice(digest.as_ref());
}
}
}
}
/// Implements `Signer` via [`ring`](https://briansmith.org/rustdoc/ring/signature/index.html)
#[cfg(feature = "signing")]
pub struct RingSigner;
#[cfg(feature = "signing")]
impl Signer for RingSigner {
fn sign(
&self,
algorithm: SigningAlgorithm,
key: Key<'_>,
data: &[u8],
) -> Result<Vec<u8>, Error> {
match algorithm {
SigningAlgorithm::RsaSha256 => {
let key_pair = match key {
Key::Pkcs8(key) => ring::signature::RsaKeyPair::from_pkcs8(key),
Key::Der(key) => ring::signature::RsaKeyPair::from_der(key),
Key::Hmac(_) => {
return Err(Error::KeyRejected(
"HMAC cannot be used with RSA signing".to_owned(),
))
}
}?;
let mut signature = vec![0; key_pair.public_modulus_len()];
let rng = ring::rand::SystemRandom::new();
key_pair.sign(
&ring::signature::RSA_PKCS1_SHA256,
&rng,
data,
&mut signature,
)?;
Ok(signature)
}
}
}
}
#[cfg(test)]
mod test {
#[test]
fn loads_svc_account() {
use super::KeyProvider;
let acct = super::ServiceAccount::load_json_file("./tests/test_account.json").unwrap();
match acct.key() {
super::Key::Pkcs8(_) => {}
key => panic!("invalid key format {:?}", key),
}
assert_eq!(
acct.authorizer(),
"real-address@very-good-project-id.iam.gserviceaccount.com"
);
}
}
|
pub mod art;
pub mod closure;
mod find_crate;
mod flow;
mod json;
mod mutex;
pub mod panic;
mod rectangle;
pub mod string;
mod tuples;
|
#![feature(proc_macro_hygiene, decl_macro)]
mod blockchain;
mod payload;
mod utils;
mod db;
use blockchain::block::*;
use blockchain::chain::*;
use payload::data::Transaction;
use chrono::prelude::*;
use rocket::http::Status;
#[macro_use] extern crate rocket;
#[post("/add", data = "<transaction>")]
async fn add_transaction(transaction: String) -> Status{
let chain: Chain = Chain::new();
let mut block: Block = Block::new();
let mut data: Vec<Transaction> = Vec::new();
let t: Transaction = serde_json::from_str(&transaction).unwrap();
// Check if transaction is signed correctly
if utils::crypto::verify_transaction(&t) == false {
return Status::BadRequest;
}
data.push(t);
// Get time
let time: DateTime<Local> = Local::now();
block.initialize(data, time.to_string());
// Execute the mining and adding to blockchain async
tokio::spawn(async move {
add_block_to_chain(block, chain).await;
});
return Status::Accepted;
}
#[get("/chain")]
fn get_chain() -> String {
let chain: Chain = Chain::new();
return chain.print();
}
async fn add_block_to_chain(mut block: Block, mut chain: Chain) {
println!("Adding blocks...");
block.mine();
chain.add(block);
println!("Added blocks");
}
#[tokio::main]
async fn main() {
// TODO: remove this
let t = Transaction{sender: "065sjdfsdf45".to_string(), receiver: "34h3453h345".to_string(), amount: "4.56".to_string(), signature: vec![0, 0, 0]};
println!("{}", serde_json::to_string(&t).unwrap());
rocket::ignite().mount("/", routes![add_transaction, get_chain]).launch().await.ok();
}
|
//
// Copyright (C) 2020 Abstract Horizon
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Apache License v2.0
// which accompanies this distribution, and is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// Contributors:
// Daniel Sendula - initial API and implementation
//
use byteorder::{ByteOrder, LittleEndian};
use phf::phf_map;
use rppal::i2c::I2c;
const _CTRL_REG1: u8 = 0x20;
const _CTRL_REG2: u8 = 0x21;
const _CTRL_REG3: u8 = 0x22;
const _CTRL_REG4: u8 = 0x23;
const _CTRL_REG5: u8 = 0x24;
const _REFERENCE: u8 = 0x25;
const _OUT_TEMP: u8 = 0x26;
const _STATUS_REG: u8 = 0x27;
const _OUT_X_L: u8 = 0x28;
const _OUT_X_H: u8 = 0x29;
const _OUT_Y_L: u8 = 0x2A;
const _OUT_Y_H: u8 = 0x2B;
const _OUT_Z_L: u8 = 0x2C;
const _OUT_Z_H: u8 = 0x2D;
const _FIFO_CTRL_REG: u8 = 0x2E;
const _FIFO_SRC_REG: u8 = 0x2F;
const _INT1_CFG: u8 = 0x30;
const _INT1_SRC: u8 = 0x31;
const _INT1_TSH_XH: u8 = 0x32;
const _INT1_TSH_XL: u8 = 0x33;
const _INT1_TSH_YH: u8 = 0x34;
const _INT1_TSH_YL: u8 = 0x35;
const _INT1_TSH_ZH: u8 = 0x36;
const _INT1_TSH_ZL: u8 = 0x37;
const _INT1_DURATION: u8 = 0x38;
const _FREQ_BANDWIDTH_100_12_5: u8 = 0x00;
const _FREQ_BANDWIDTH_100_25: u8 = 0x10;
const _FREQ_BANDWIDTH_200_12_5: u8 = 0x40;
const _FREQ_BANDWIDTH_200_25: u8 = 0x50;
const _FREQ_BANDWIDTH_200_50: u8 = 0x60;
const _FREQ_BANDWIDTH_200_70: u8 = 0x70;
const _FREQ_BANDWIDTH_400_20: u8 = 0x80;
const _FREQ_BANDWIDTH_400_25: u8 = 0x90;
const _FREQ_BANDWIDTH_400_50: u8 = 0xA0;
const _FREQ_BANDWIDTH_400_110: u8 = 0xB0;
const _FREQ_BANDWIDTH_800_30: u8 = 0xC0;
const _FREQ_BANDWIDTH_800_35: u8 = 0xD0;
const _FREQ_BANDWIDTH_800_50: u8 = 0xE0;
const _FREQ_BANDWIDTH_800_111: u8 = 0xF0;
// #[derive(Clone)]
pub struct DataPoint {
pub dx: i16,
pub dy: i16,
pub dz: i16,
pub status: u16,
pub fifo_status: u8
}
impl DataPoint {
// fn empty() -> DataPoint {
// DataPoint { dx: 0, dy: 0, dz: 0, status: 0, fifo_status: 0 }
// }
fn new(dx: i16, dy: i16, dz: i16, status: u16, fifo_status: u8) -> DataPoint {
DataPoint { dx, dy, dz, status, fifo_status }
}
}
const FREQ_100: phf::Map<&'static str, u8> = phf_map! {"_" => 0x00, "12.5" => 0, "25" => 0x10};
const FREQ_200: phf::Map<&'static str, u8> = phf_map! {"_" => 0x40, "12.5" => 0, "25" => 0x10, "50" => 0x20, "70" => 0x30};
const FREQ_400: phf::Map<&'static str, u8> = phf_map! {"_" => 0x80, "20" => 0, "25" => 0x10, "50" => 0x20, "110" => 0x30};
const FREQ_800: phf::Map<&'static str, u8> = phf_map! {"_" => 0xC0, "30" => 0, "35" => 0x10, "50" => 0x20, "110" => 0x30};
const ALLOWED_FREQ_BANDWIDTH_COMBINATIONS: phf::Map<u16, phf::Map<&'static str, u8>> = phf_map! {
100u16 => FREQ_100,
200u16 => FREQ_200,
400u16 => FREQ_400,
800u16 => FREQ_800,
};
pub struct L3G4200D {
bus: I2c,
// address: u8,
freq_u16: u16,
pub freq: f64,
pub bandwidth: &'static str,
pub combine_filter: f64,
pub px: f64,
pub py: f64,
pub pz: f64,
pub cx: f64,
pub cy: f64,
pub cz: f64,
// buffer_len_in_time: f64,
// data_buffer: Vec<DataPoint>,
sensitivity: f64,
}
impl L3G4200D {
pub fn new(address: u8, freq: u16, bandwidth: &'static str, combine_filter: f64) -> L3G4200D {
match ALLOWED_FREQ_BANDWIDTH_COMBINATIONS.get(&freq) {
Some(map) => if !map.contains_key(&bandwidth) {
// panic!("Bandwidth {} for frequency {} can be only one of: {}", bandwidth, freq, map);
panic!("L3G4200D: Bandwidth {} for frequency {} is not valid.", bandwidth, freq);
},
None => panic!("L3G4200D: Fequency can be only one of: 100, 200, 400 or 800; but got {}", freq)
}
let mut bus = I2c::with_bus(1).expect("L3G4200D: Cannot initialise i2c bus 1");
bus.set_slave_address(address as u16).unwrap_or_else(|_| panic!("L3G4200D: Cannot set slave address {}", address));
let result = L3G4200D {
bus,
freq_u16: freq,
freq: freq as f64,
bandwidth,
combine_filter,
px: 0.0, py: 0.0, pz: 0.0,
cx: 0.0, cy: 0.0, cz: 0.0,
sensitivity: 0.00875,
};
result.init_gyro();
result
}
fn init_gyro(&self) {
let selected_freq = ALLOWED_FREQ_BANDWIDTH_COMBINATIONS.get(&self.freq_u16).unwrap();
let ctrl1 = 0xf + selected_freq.get("_").unwrap() + selected_freq.get(self.bandwidth).unwrap();
self.bus.smbus_write_byte(_CTRL_REG1, ctrl1).expect("L3G4200D: Cannot set REG1 on i2c"); // Output data rate 800Hz, freq cut-off 50 (Hz?), normal mode (not power down), all axes (x, y, z) enabled
self.bus.smbus_write_byte(_CTRL_REG2, 0x0).expect("L3G4200D: Cannot set REG2 on i2c");
self.bus.smbus_write_byte(_CTRL_REG3, 0x0).expect("L3G4200D: Cannot set REG3 on i2c");
self.bus.smbus_write_byte(_CTRL_REG4, 0x80).expect("L3G4200D: Cannot set REG4 on i2c"); // Not block (continuous update), LSB @ lower address, FSR 500dps, self test disabled, i2c interface
self.bus.smbus_write_byte(_CTRL_REG5, 0x40).expect("L3G4200D: Cannot set REG5 on i2c"); // FIFO enabled
self.bus.smbus_write_byte(_FIFO_CTRL_REG, 0x60).expect("L3G4200D: Cannot set _FIFO_CTRL_REG on i2c"); // FIFO Stream mode
println!("Initialised L3G4200D i2c device.");
}
fn read_data(&self, status: u16, fifo_status: u8) -> DataPoint {
let command: [u8; 1] = [_OUT_X_L + 0x80];
let mut buf = [0u8; 6];
let _ = self.bus.write_read(&command, &mut buf).expect("Cannot read 6 bytes from i2c");
let dx = LittleEndian::read_i16(&buf[0..2]);
let dy = LittleEndian::read_i16(&buf[2..4]);
let dz = LittleEndian::read_i16(&buf[4..6]);
DataPoint::new(dx, dy, dz, status, fifo_status)
}
pub fn read_deltas(&mut self) -> Vec<DataPoint> {
let mut result_data: Vec<DataPoint> = vec![];
let mut waited_for_data = false;
let mut status: u16 = self.bus.smbus_read_byte(_STATUS_REG).expect("L3G4200D: Cannot read status from i2c bus") as u16;
while status & 0xf != 0xf {
// TODO add check for imdefinite wait
waited_for_data = true;
status = self.bus.smbus_read_byte(_STATUS_REG).expect("L3G4200D: Cannot status byte from i2c bus") as u16;
}
if waited_for_data {
status += 256
}
let mut fifo_status: u8 = self.bus.smbus_read_byte(_FIFO_SRC_REG).expect("L3G4200D: Cannot read fifo_status from i2c bus");
while fifo_status & 0x1f != 0 {
// TODO add check for imdefinite wait
let data_point = self.read_data(status, fifo_status);
result_data.push(data_point);
fifo_status = self.bus.smbus_read_byte(_FIFO_SRC_REG).expect("L3G4200D: Cannot read fifo_status from i2c bus");
}
for data_point in &result_data {
let x = (data_point.dx as f64 - self.cx) * self.sensitivity;
let y = (data_point.dy as f64 - self.cy) * self.sensitivity;
let z = (data_point.dz as f64 - self.cz) * self.sensitivity;
let invert_combine_filter = 1.0 - self.combine_filter;
self.px = x * self.combine_filter + invert_combine_filter * self.px;
self.py = y * self.combine_filter + invert_combine_filter * self.py;
self.pz = z * self.combine_filter + invert_combine_filter * self.pz;
}
result_data
}
} |
use std::fs::File;
use std::collections::HashMap;
use std::io::{BufRead, BufReader};
fn print_eris(eris : u32) {
let mut power2 = 1;
for _x in 0..5 {
for _y in 0..5 {
if (eris & power2) > 0 {
print!("#");
} else {
print!(".");
}
power2 *= 2;
}
println!("");
}
}
fn evolve_eris_one(eris : u32, eris_out : u32, eris_in : u32) -> u32 {
let mut new_eris : u32 = 0;
let mut power2 = 1;
for x in 0..5 {
for y in 0..5 {
if x == 2 && y == 2 {
power2 *= 2;
continue;
}
let mut adjacent_info = 0;
if x > 0 {
if x == 3 && y == 2 {
for i in 20..25 {
adjacent_info += if (eris_in & (1u32 << i)) > 0 { 1 } else { 0 };
}
} else {
let new_n = power2 >> 5;
adjacent_info += if (eris & new_n) > 0 { 1 } else { 0 };
}
} else {
let new_n = 1u32 << 7;
adjacent_info += if (eris_out & new_n) > 0 { 1 } else { 0 };
}
if x < 4 {
if x == 1 && y == 2 {
for i in 0..5 {
adjacent_info += if eris_in & (1u32 << i) > 0 { 1 } else { 0 };
}
} else {
let new_n = power2 << 5;
adjacent_info += if (eris & new_n) > 0 { 1 } else { 0 };
}
} else {
let new_n = 1u32 << 17;
adjacent_info += if (eris_out & new_n) > 0 { 1 } else { 0 };
}
if y > 0 {
if x == 2 && y == 3 {
for i in 0..5 {
adjacent_info += if (eris_in & (1u32 << (5*i + 4))) > 0 { 1 } else { 0 };
}
} else {
let new_n = power2 >> 1;
adjacent_info += if (eris & new_n) > 0 { 1 } else { 0 };
}
} else {
let new_n = 1u32 << 11;
adjacent_info += if (eris_out & new_n) > 0 { 1 } else { 0 };
}
if y < 4 {
if x == 2 && y == 1 {
for i in 0..5 {
adjacent_info += if (eris_in & (1u32 << (5*i))) > 0 { 1 } else { 0 };
}
} else {
let new_n = power2 << 1;
adjacent_info += if (eris & new_n) > 0 { 1 } else { 0 };
}
} else {
let new_n = 1u32 << 13;
adjacent_info += if (eris_out & new_n) > 0 { 1 } else { 0 };
}
if (eris & power2) > 0 {
new_eris |= if adjacent_info == 1 { power2 } else { 0 };
} else {
new_eris |= if adjacent_info == 1 || adjacent_info == 2 { power2 } else { 0 };
}
power2 *= 2;
}
}
return new_eris;
}
fn evolve_eris(eris_levels : &HashMap<i32, u32>) -> HashMap<i32, u32> {
let mut level : i32 = 0;
let mut new_eris_levels : HashMap<i32, u32> = HashMap::new();
loop {
if !eris_levels.contains_key(&level) && !eris_levels.contains_key(&(level - 1)) {
break;
}
let eris_0 = match eris_levels.get(&level) {
Some(x) => *x,
None => 0
};
let eris_out = match eris_levels.get(&(level - 1)) {
Some(x) => *x,
None => 0
};
let eris_in = match eris_levels.get(&(level + 1)) {
Some(x) => *x,
None => 0
};
let new_eris = evolve_eris_one(eris_0, eris_out, eris_in);
new_eris_levels.insert(level, new_eris);
if level > 0 {
let n_level = -level;
let eris_n0 = match eris_levels.get(&n_level) {
Some(x) => *x,
None => 0
};
let eris_nout = match eris_levels.get(&(n_level - 1)) {
Some(x) => *x,
None => 0
};
let eris_nin = match eris_levels.get(&(n_level + 1)) {
Some(x) => *x,
None => 0
};
let new_neris = evolve_eris_one(eris_n0, eris_nout, eris_nin);
new_eris_levels.insert(n_level, new_neris);
}
level += 1;
}
return new_eris_levels;
}
fn count_bugs(eris : u32) -> u32 {
let mut counter :u32 = 0;
for i in 0..25 {
counter += if (eris & (1 << i)) > 0 { 1 } else { 0 };
}
return counter;
}
fn main() {
let filename = "../part1/src/input";
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut eris : u32 = 0;
let mut power2 : u32 = 1;
// Read the file line by line using the lines() iterator from std::io::BufRead.
for (_, line) in reader.lines().enumerate() {
let line = line.unwrap(); // Ignore errors.
if line.trim().len() == 0 {
break;
}
for c in line.chars() {
if c == '#' {
eris |= power2;
}
power2 *= 2;
}
}
let mut eris_levels : HashMap<i32, u32> = HashMap::new();
eris_levels.insert(0, eris);
for _i in 0..200 {
eris_levels = evolve_eris(&mut eris_levels);
}
println!("{:?}", eris_levels);
let mut bugs : u32 = 0;
for e in eris_levels.iter() {
bugs += count_bugs(*e.1);
}
println!("Solution bugs: {}", bugs);
}
|
use serde::{Deserialize, Serialize};
use crate::errors;
use crate::listener::*;
use crate::token::*;
use bytes::Buf;
use futures::future::TryFutureExt;
use hyper::body::HttpBody;
use hyper::client::*;
use hyper::http::StatusCode;
use hyper::{Body, Request, Response, Uri};
use hyper_rustls::HttpsConnector;
use lazy_static::*;
use mime::Mime;
use rvstruct::ValueStruct;
use std::collections::HashMap;
use std::io::Read;
use url::Url;
#[derive(Debug)]
pub struct SlackClient {
pub http_api: SlackClientHttpApi,
}
#[derive(Debug)]
pub struct SlackClientHttpApi {
connector: Client<HttpsConnector<HttpConnector>>,
}
#[derive(Debug)]
pub struct SlackClientSession<'a> {
pub http_api: SlackClientHttpSessionApi<'a>,
client: &'a SlackClient,
token: &'a SlackApiToken,
}
#[derive(Debug)]
pub struct SlackClientHttpSessionApi<'a> {
client: &'a SlackClient,
token: &'a SlackApiToken,
}
pub type ClientResult<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
struct SlackEnvelopeMessage {
ok: bool,
error: Option<String>,
warnings: Option<Vec<String>>,
}
lazy_static! {
pub static ref SLACK_HTTP_EMPTY_GET_PARAMS: Vec<(&'static str, Option<&'static String>)> =
vec![];
}
impl SlackClientHttpApi {
const SLACK_API_URI_STR: &'static str = "https://slack.com/api";
fn new() -> Self {
let https_connector = HttpsConnector::with_native_roots();
let http_client = Client::builder().build::<_, hyper::Body>(https_connector);
Self {
connector: http_client,
}
}
pub(crate) fn create_method_uri_path(method_relative_uri: &str) -> String {
format!("{}/{}", Self::SLACK_API_URI_STR, method_relative_uri)
}
pub(crate) fn create_url(url_str: &str) -> Uri {
url_str.parse().unwrap()
}
pub(crate) fn create_url_with_params<'p, PT, TS>(url_str: &str, params: &'p PT) -> Uri
where
PT: std::iter::IntoIterator<Item = (&'p str, Option<&'p TS>)> + Clone,
TS: std::string::ToString + 'p,
{
let url_query_params: Vec<(String, String)> = params
.clone()
.into_iter()
.map(|(k, vo)| vo.map(|v| (k.to_string(), v.to_string())))
.flatten()
.collect();
Url::parse_with_params(url_str, url_query_params)
.unwrap()
.as_str()
.parse()
.unwrap()
}
pub fn parse_query_params(request: &Request<Body>) -> HashMap<String, String> {
request
.uri()
.query()
.map(|v| {
url::form_urlencoded::parse(v.as_bytes())
.into_owned()
.collect()
})
.unwrap_or_else(HashMap::new)
}
pub fn hyper_redirect_to(
url: &str,
) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> {
Response::builder()
.status(hyper::http::StatusCode::FOUND)
.header(hyper::header::LOCATION, url)
.body(Body::empty())
.map_err(|e| e.into())
}
fn setup_token_auth_header(
request_builder: hyper::http::request::Builder,
token: Option<&SlackApiToken>,
) -> hyper::http::request::Builder {
if token.is_none() {
request_builder
} else {
let token_header_value = format!("Bearer {}", token.unwrap().token_value.value());
request_builder.header(hyper::header::AUTHORIZATION, token_header_value)
}
}
pub(crate) fn setup_basic_auth_header(
request_builder: hyper::http::request::Builder,
username: &str,
password: &str,
) -> hyper::http::request::Builder {
let header_value = format!(
"Basic {}",
base64::encode(format!("{}:{}", username, password))
);
request_builder.header(hyper::header::AUTHORIZATION, header_value)
}
pub(crate) fn create_http_request(
uri: Uri,
method: hyper::http::Method,
) -> hyper::http::request::Builder {
hyper::http::request::Builder::new()
.method(method)
.uri(uri)
.header("accept-charset", "utf-8")
}
async fn http_body_to_string<T>(body: T) -> ClientResult<String>
where
T: HttpBody,
T::Error: std::error::Error + Sync + Send + 'static,
{
let http_body = hyper::body::aggregate(body).await?;
let mut http_reader = http_body.reader();
let mut http_body_str = String::new();
http_reader.read_to_string(&mut http_body_str)?;
Ok(http_body_str)
}
fn http_response_content_type<RS>(response: &Response<RS>) -> Option<Mime> {
let http_headers = response.headers();
http_headers.get(hyper::header::CONTENT_TYPE).map(|hv| {
let hvs = hv.to_str().unwrap();
hvs.parse::<Mime>().unwrap()
})
}
pub(crate) async fn decode_signed_response(
req: Request<Body>,
signature_verifier: &SlackEventSignatureVerifier,
) -> ClientResult<String> {
let headers = &req.headers().clone();
let req_body = req.into_body();
match (
headers.get(SlackEventSignatureVerifier::SLACK_SIGNED_HASH_HEADER),
headers.get(SlackEventSignatureVerifier::SLACK_SIGNED_TIMESTAMP),
) {
(Some(received_hash), Some(received_ts)) => {
Self::http_body_to_string(req_body)
.and_then(|body| async {
signature_verifier
.verify(
&received_hash.to_str().unwrap(),
&body,
&received_ts.to_str().unwrap(),
)
.map(|_| body)
.map_err(|e| e.into())
})
.await
}
_ => Err(Box::new(SlackEventAbsentSignatureError::new())),
}
}
pub(crate) async fn send_webapi_request<RS>(&self, request: Request<Body>) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
{
let http_res = self.connector.request(request).await?;
let http_status = http_res.status();
let http_content_type = Self::http_response_content_type(&http_res);
let http_body_str = Self::http_body_to_string(http_res).await?;
match http_status {
StatusCode::OK
if http_content_type.iter().all(|response_mime| {
response_mime.type_() == mime::APPLICATION
&& response_mime.subtype() == mime::JSON
}) =>
{
let slack_message: SlackEnvelopeMessage =
serde_json::from_str(http_body_str.as_str())?;
if slack_message.error.is_none() {
let decoded_body = serde_json::from_str(http_body_str.as_str())?;
Ok(decoded_body)
} else {
Err(errors::SlackClientError::ApiError(
errors::SlackClientApiError::new(slack_message.error.unwrap())
.opt_warnings(slack_message.warnings)
.with_http_response_body(http_body_str),
)
.into())
}
}
StatusCode::OK => serde_json::from_str("{}").map_err(|e| e.into()),
_ => Err(errors::SlackClientError::HttpError(
errors::SlackClientHttpError::new(http_status)
.with_http_response_body(http_body_str),
)
.into()),
}
}
pub async fn http_get_uri<'a, RS>(
&self,
full_uri: Uri,
token: Option<&'a SlackApiToken>,
) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
{
let base_http_request = Self::create_http_request(full_uri, hyper::http::Method::GET);
let http_request = Self::setup_token_auth_header(base_http_request, token);
let body = self
.send_webapi_request(http_request.body(Body::empty())?)
.await?;
Ok(body)
}
async fn http_get_token<'a, 'p, RS, PT, TS>(
&self,
method_relative_uri: &str,
params: &'p PT,
token: Option<&'a SlackApiToken>,
) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
PT: std::iter::IntoIterator<Item = (&'p str, Option<&'p TS>)> + Clone,
TS: std::string::ToString + 'p,
{
let full_uri = Self::create_url_with_params(
&Self::create_method_uri_path(&method_relative_uri),
params,
);
self.http_get_uri(full_uri, token).await
}
pub async fn http_get<'p, RS, PT, TS>(
&self,
method_relative_uri: &str,
params: &'p PT,
) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
PT: std::iter::IntoIterator<Item = (&'p str, Option<&'p TS>)> + Clone,
TS: std::string::ToString + 'p,
{
self.http_get_token(&method_relative_uri, params, None)
.await
}
pub async fn http_post_uri<'a, RQ, RS>(
&self,
full_uri: Uri,
request_body: &RQ,
token: Option<&'a SlackApiToken>,
) -> ClientResult<RS>
where
RQ: serde::ser::Serialize,
RS: for<'de> serde::de::Deserialize<'de>,
{
let post_json = serde_json::to_string(&request_body)?;
let base_http_request = Self::create_http_request(full_uri, hyper::http::Method::POST)
.header("content-type", "application/json; charset=utf-8");
let http_request = Self::setup_token_auth_header(base_http_request, token);
let response_body = self
.send_webapi_request(http_request.body(post_json.into())?)
.await?;
Ok(response_body)
}
async fn http_post_token<'a, RQ, RS>(
&self,
method_relative_uri: &str,
request: &RQ,
token: Option<&'a SlackApiToken>,
) -> ClientResult<RS>
where
RQ: serde::ser::Serialize,
RS: for<'de> serde::de::Deserialize<'de>,
{
let full_uri = Self::create_url(&SlackClientHttpApi::create_method_uri_path(
&method_relative_uri,
));
self.http_post_uri(full_uri, &request, token).await
}
pub async fn http_post<RQ, RS>(
&self,
method_relative_uri: &str,
request: &RQ,
) -> ClientResult<RS>
where
RQ: serde::ser::Serialize,
RS: for<'de> serde::de::Deserialize<'de>,
{
self.http_post_token(method_relative_uri, &request, None)
.await
}
}
impl SlackClient {
pub fn new() -> Self {
Self {
http_api: SlackClientHttpApi::new(),
}
}
pub fn open_session<'a>(&'a self, token: &'a SlackApiToken) -> SlackClientSession<'a> {
let http_session_api = SlackClientHttpSessionApi {
client: self,
token,
};
SlackClientSession {
client: self,
token,
http_api: http_session_api,
}
}
}
impl<'a> SlackClientHttpSessionApi<'a> {
pub async fn http_get_uri<RS, PT, TS>(&self, full_uri: Uri) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
{
self.client
.http_api
.http_get_uri(full_uri, Some(&self.token))
.await
}
pub async fn http_get<'p, RS, PT, TS>(
&self,
method_relative_uri: &str,
params: &'p PT,
) -> ClientResult<RS>
where
RS: for<'de> serde::de::Deserialize<'de>,
PT: std::iter::IntoIterator<Item = (&'p str, Option<&'p TS>)> + Clone,
TS: std::string::ToString + 'p,
{
self.client
.http_api
.http_get_token(&method_relative_uri, params, Some(&self.token))
.await
}
pub async fn http_post<RQ, RS>(
&self,
method_relative_uri: &str,
request: &RQ,
) -> ClientResult<RS>
where
RQ: serde::ser::Serialize,
RS: for<'de> serde::de::Deserialize<'de>,
{
self.client
.http_api
.http_post_token(&method_relative_uri, &request, Some(&self.token))
.await
}
pub async fn http_post_uri<RQ, RS>(&self, full_uri: Uri, request: &RQ) -> ClientResult<RS>
where
RQ: serde::ser::Serialize,
RS: for<'de> serde::de::Deserialize<'de>,
{
self.client
.http_api
.http_post_uri(full_uri, &request, Some(&self.token))
.await
}
}
|
use std::str::FromStr;
use chrono::prelude::*;
use regex::Regex;
const REGEX_STRING: &str =
r"(?P<date>[\d/]{10} [\d:]{8}) \d+ (?P<id>\w+) \[(?P<log_string>[^\[]+)\] :? ?(?P<message>.*)";
const TIME_PARSE_STRING: &str = "%Y/%m/%d %H:%M:%S";
#[derive(Debug, PartialEq)]
pub struct ClientLogLine {
pub date: DateTime<Local>,
pub message: String,
}
impl FromStr for ClientLogLine {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
lazy_static!{
static ref RE: Regex = Regex::new(REGEX_STRING).unwrap();
}
if let Some(caps) = RE.captures(s.trim()) {
let date = Local
.datetime_from_str(caps.name("date").unwrap().as_str(), TIME_PARSE_STRING)
.map_err(|e| format!("{:?}", e))?;
Ok(Self {
date: date,
message: caps.name("message").unwrap().as_str().into(),
})
} else {
Err(format!("Regex didn't match for line. {}", s))
}
}
}
#[test]
fn test_regex() {
const LINE: &str = "2018/03/22 22:44:20 536347968 d9 [INFO Client 8672] Connecting to instance server at 159.122.142.230:6112";
let re = Regex::new(REGEX_STRING);
assert!(re.is_ok());
let re = re.unwrap();
let caps = re.captures(LINE);
assert!(caps.is_some());
let caps = caps.unwrap();
let date_string = caps.name("date").unwrap().as_str();
let message = caps.name("message").unwrap().as_str();
assert_eq!("2018/03/22 22:44:20", date_string);
assert_eq!(
"Connecting to instance server at 159.122.142.230:6112",
message
);
}
#[test]
fn test_date_parse() {
const DATE_STRING: &str = "2018-03-22T22:44:20Z";
let _: DateTime<Local> = DATE_STRING.parse().unwrap();
}
#[test]
fn test_client_log_line_from_str() {
const LINE: &str = "2018/03/22 22:44:20 536347968 d9 [INFO Client 8672] Connecting to instance server at 159.122.142.230:6112";
let cll: Result<ClientLogLine, _> = LINE.parse();
let cll = cll.unwrap();
let expected_cll = ClientLogLine {
date: Local
.datetime_from_str("2018/03/22 22:44:20", TIME_PARSE_STRING)
.unwrap(),
message: "Connecting to instance server at 159.122.142.230:6112".into(),
};
assert_eq!(cll, expected_cll);
}
|
use colored::*;
const ART: &str = r###"
}wJ@g@Wg@gg _
,g1@@@W%%gd6%W@@@gg
gg@@Q;_________ "%@@gm
g@@@@@@@@@@@@@@@@g `@@Ww
w@@jFc}@@@L```"@@@@O#Qj@g=
g@@O }@@@@@@@@@@@_ 1@Wg
g@@C }@@@L``'1@@@W_ &@@@_
l@@@@@@@@@@@ @@@@@@@@@Q
`F@@Q)$"???? *TDD@@@U
]@@Qj@_ _@jF@@
1%1@@@@@@@@@@HW
*`1C'O "
"###;
fn exc(exc: &str) -> Result<std::process::Output, std::io::Error> {
let exc: Vec<&str> = exc.split_whitespace().collect();
let mut cmd = std::process::Command::new(exc[0]);
cmd.args(&exc[1..exc.len()])
.output()
}
fn get_ver(cmd: &str) -> String {
let get_ver = match exc(cmd) {
Ok(ver) => ver.stdout,
Err(_) => "not present".as_bytes().to_vec(),
};
let mut get_ver = std::str::from_utf8(&get_ver)
.unwrap()
.lines();
match get_ver.next() {
Some(v) => v.to_string(),
None => "not present.".to_string(),
}
}
fn cargo_installs() -> String {
let cargo_installs = match exc("cargo install --list") {
Ok(installs) => installs.stdout,
Err(_) => "not present".as_bytes().to_vec(),
};
let cargo_installs = std::str::from_utf8(&cargo_installs)
.unwrap()
.lines();
String::from(format!("{}", cargo_installs.count() / 2))
}
fn print(info: Vec<String>) {
let mut lines = ART.lines();
let mut i = 0;
let empty = String::from("");
loop {
match lines.next() {
Some(line) => {
println!("{}{}",
line.red(),
match i <= info.len() - 1 {
true => {
i = i + 1;
&info[i - 1]
},
false => &empty,
});
},
None => break,
}
}
}
fn main() {
let rust_ver = get_ver("rustc -vV");
let sys_info = sys_info::linux_os_release()
.unwrap();
let mem = sys_info::mem_info()
.unwrap();
let mem_used = (mem.total - mem.avail) / 1024;
let mem_total = mem.total / 1024;
let mut info: Vec<String> = vec![];
info.push("".to_string());
info.push(format!("{}{}{}", whoami::username().bold(), "@".bright_purple().bold(), whoami::hostname().bold()));
info.push(format!("{}", "━━━━━━━━━━━━━━━".blue().bold()));
info.push(format!("{} {}", "rust version".purple(), rust_ver));
info.push(format!("{} {}", "cargo version".purple(), get_ver("cargo -vV")));
info.push(format!("{} {}", "rustup version".purple(), get_ver("rustup -vV")));
let rust_ver: Vec<&str> = rust_ver.split(" ").collect();
let rust_ver: &str = rust_ver[1];
let chan = match semver::Version::parse(rust_ver) {
Ok(ver) => {
match ver.pre.first() {
None => "stable",
Some(semver::Identifier::AlphaNumeric(s)) => &s,
Some(_) => "unknown",
}.to_string()
},
Err(_) => "not present".to_string(),
};
info.push(format!("{} {}", "rust channel".purple(), chan));
info.push(format!("{} {}", "cargo installs".purple(), cargo_installs()));
info.push(format!("{} {}", "os".purple(), match sys_info.pretty_name {
Some(os) => os,
None => "".to_string(),
}));
info.push(format!("{} {}", "release".purple(), sys_info::os_release().unwrap()));
info.push(format!("{} {}MiB/{}MiB ({:.1}%)", "memory".purple(), mem_used, mem_total, (mem_used as f32 / mem_total as f32) * 100.0));
info.push("".to_string());
info.push(format!("{}{}{}{}{}{}{}{}", "███".black(), "███".red(), "███".green(), "███".yellow(), "███".blue(), "███".magenta(), "███".cyan(), "███".white()));
print(info);
}
|
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum MediaType {
Anime,
Manga,
}
impl std::fmt::Display for MediaType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self {
MediaType::Anime => "ANIME",
MediaType::Manga => "MANGA",
};
write!(f, "{}", string)
}
}
impl From<&str> for MediaType {
fn from(typ: &str) -> Self {
match typ.to_lowercase().as_ref() {
"manga" => MediaType::Manga,
_ => MediaType::Anime,
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MediaFormat {
Tv,
TvShort,
Movie,
Special,
Ova,
Ona,
Music,
Manga,
Novel,
OneShot,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MediaStatus {
Finished,
Releasing,
NotYetReleased,
Cancelled,
}
impl MediaStatus {
pub fn to_discord_emoji(&self) -> String {
match self {
MediaStatus::Finished => ":white_small_square:",
MediaStatus::Releasing => ":small_blue_diamond:",
MediaStatus::NotYetReleased => ":small_orange_diamond:",
MediaStatus::Cancelled => ":black_small_square:",
}
.to_string()
}
pub fn to_string_with_emoji(&self) -> String {
format!("{}: {}", self.to_string(), self.to_discord_emoji())
}
}
impl std::fmt::Display for MediaStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self {
MediaStatus::Finished => "Finished",
MediaStatus::Releasing => "Releasing",
MediaStatus::NotYetReleased => "Not Yet Released",
MediaStatus::Cancelled => "Cancelled",
};
write!(f, "{}", string)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum MediaListStatus {
Current,
Planning,
Completed,
Dropped,
Paused,
Repeating,
}
impl std::fmt::Display for MediaListStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self {
MediaListStatus::Current => "Current",
MediaListStatus::Planning => "Planning",
MediaListStatus::Completed => "Completed",
MediaListStatus::Dropped => "Dropped",
MediaListStatus::Paused => "Paused",
MediaListStatus::Repeating => "Repeating",
};
write!(f, "{}", string)
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MediaSeason {
Winter,
Spring,
Summer,
Fall,
}
impl std::fmt::Display for MediaSeason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self {
MediaSeason::Winter => "Winter",
MediaSeason::Spring => "Spring",
MediaSeason::Summer => "Summer",
MediaSeason::Fall => "Fall",
};
write!(f, "{}", string)
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MediaSource {
Anime,
Doujinshi,
LightNovel,
Manga,
Novel,
Other,
Original,
VideoGame,
VisualNovel,
}
|
pub use crate::{
html::attributes::*,
html::events::*,
html::*,
platform::{self, *},
time::Time,
};
pub use wasm_bindgen::prelude::*;
|
//! `encrypted-sled` is a drop in replacement / wrapper around the amazing
//! [`sled`](https://crates.io/crates/sled) embedded database. Just configure with an encryption
//! and use normally.
//!
//! # Examples
//!
//! ```
//! # let _ = std::fs::remove_dir_all("my_db");
//! let cipher = encrypted_sled::EncryptionCipher::<chacha20::ChaCha20>::new_from_slices(
//! b"an example very very secret key.",
//! b"secret nonce",
//! encrypted_sled::EncryptionMode::default(),
//! )
//! .unwrap();
//! let db = encrypted_sled::open("my_db", cipher).unwrap();
//!
//! // insert and get
//! db.insert(b"yo!", b"v1");
//! assert_eq!(&db.get(b"yo!").unwrap().unwrap(), b"v1");
//!
//! // Atomic compare-and-swap.
//! db.compare_and_swap(
//! b"yo!", // key
//! Some(b"v1"), // old value, None for not present
//! Some(b"v2"), // new value, None for delete
//! )
//! .unwrap();
//!
//! // Iterates over key-value pairs, starting at the given key.
//! let scan_key: &[u8] = b"a non-present key before yo!";
//! let mut iter = db.range(scan_key..);
//! assert_eq!(&iter.next().unwrap().unwrap().0, b"yo!");
//! assert_eq!(iter.next(), None);
//!
//! db.remove(b"yo!");
//! assert_eq!(db.get(b"yo!"), Ok(None));
//!
//! let other_tree = db.open_tree(b"cool db facts").unwrap();
//! other_tree.insert(
//! b"k1",
//! &b"a Db acts like a Tree due to implementing Deref<Target = Tree>"[..]
//! ).unwrap();
//! # let _ = std::fs::remove_dir_all("my_db");
//! ```
//!
//! # Todos
//!
//! A few things are still not implemented:
//!
//! * `TransactionalTrees` (e.g. performing a transaction on multiple trees at the same time)
//! * Database import/export
#[macro_use]
extern crate bitflags;
use cipher::generic_array;
use cipher::{CipherKey, NewCipher, Nonce, StreamCipher};
use core::fmt;
use core::future::Future;
use core::marker::PhantomData;
use core::ops;
use core::pin::Pin;
use core::task::{Context, Poll};
use core::time::Duration;
use generic_array::typenum;
use generic_array::GenericArray;
use std::path::Path;
use std::sync::mpsc::RecvTimeoutError;
use std::sync::Arc;
use typenum::Unsigned;
pub use sled::{CompareAndSwapError, Error, Event, IVec, MergeOperator, Mode};
pub type Result<T, E = sled::Error> = std::result::Result<T, E>;
bitflags! {
pub struct EncryptionMode: u32 {
const KEY = 0b0001;
const VALUE = 0b0010;
const TREE_NAME = 0b0100;
}
}
impl Default for EncryptionMode {
fn default() -> Self {
EncryptionMode::VALUE
}
}
pub struct EncryptionCipher<C>
where
C: StreamCipher + NewCipher,
{
cipher: PhantomData<C>,
key: CipherKey<C>,
nonce: Nonce<C>,
mode: EncryptionMode,
}
impl<C> EncryptionCipher<C>
where
C: StreamCipher + NewCipher,
{
pub fn new(key: CipherKey<C>, nonce: Nonce<C>, mode: EncryptionMode) -> Self {
Self {
cipher: PhantomData,
key,
nonce,
mode,
}
}
pub fn new_from_slices(
key: &[u8],
nonce: &[u8],
mode: EncryptionMode,
) -> Result<Self, cipher::errors::InvalidLength> {
let kl = C::KeySize::to_usize();
let nl = C::NonceSize::to_usize();
if key.len() != kl || nonce.len() != nl {
Err(cipher::errors::InvalidLength)
} else {
let key = GenericArray::clone_from_slice(key);
let nonce = GenericArray::clone_from_slice(nonce);
Ok(Self::new(key, nonce, mode))
}
}
#[inline]
pub fn cipher(&self) -> C {
C::new(&self.key, &self.nonce)
}
fn apply_to_data(&self, mut data: IVec, mode: EncryptionMode) -> IVec {
if self.mode.contains(mode) {
self.cipher().apply_keystream(&mut data);
}
data
}
}
impl<C> Clone for EncryptionCipher<C>
where
C: StreamCipher + NewCipher,
{
fn clone(&self) -> Self {
Self {
cipher: self.cipher,
key: self.key.clone(),
nonce: self.nonce.clone(),
mode: self.mode,
}
}
}
impl<C> fmt::Debug for EncryptionCipher<C>
where
C: StreamCipher + NewCipher,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EncryptionCipher")
.field("cipher", &core::any::type_name::<C>())
.field("mode", &self.mode)
.finish()
}
}
const DEFAULT_TREE_NAME: &[u8] = b"__sled__default";
pub trait Encryption {
fn encrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec;
fn decrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec;
#[inline]
fn encrypt<T: Into<IVec>>(&self, data: T, mode: EncryptionMode) -> IVec {
self.encrypt_ivec(data.into(), mode)
}
#[inline]
fn decrypt<T: Into<IVec>>(&self, data: T, mode: EncryptionMode) -> IVec {
self.decrypt_ivec(data.into(), mode)
}
#[inline]
fn encrypt_key<T: Into<IVec>>(&self, data: T) -> IVec {
self.encrypt(data, EncryptionMode::KEY)
}
#[inline]
fn decrypt_key<T: Into<IVec>>(&self, data: T) -> IVec {
self.decrypt(data, EncryptionMode::KEY)
}
#[inline]
fn encrypt_value<T: Into<IVec>>(&self, data: T) -> IVec {
self.encrypt(data, EncryptionMode::VALUE)
}
#[inline]
fn decrypt_value<T: Into<IVec>>(&self, data: T) -> IVec {
self.decrypt(data, EncryptionMode::VALUE)
}
fn encrypt_tree_name<T: Into<IVec>>(&self, data: T) -> IVec {
let data = data.into();
if data == DEFAULT_TREE_NAME {
return data;
}
self.encrypt(data, EncryptionMode::TREE_NAME)
}
fn decrypt_tree_name<T: Into<IVec>>(&self, data: T) -> IVec {
let data = data.into();
if data == DEFAULT_TREE_NAME {
return data;
}
self.decrypt(data, EncryptionMode::TREE_NAME)
}
fn decrypt_value_result<E>(&self, res: Result<Option<IVec>, E>) -> Result<Option<IVec>, E> {
res.map(|val| val.map(|val| self.decrypt_value(val)))
}
fn decrypt_key_value_result(
&self,
res: Result<Option<(IVec, IVec)>>,
) -> Result<Option<(IVec, IVec)>> {
res.map(|val| val.map(|(key, val)| (self.decrypt_key(key), self.decrypt_value(val))))
}
fn encrypt_event(&self, event: Event) -> Event {
match event {
Event::Insert { key, value } => Event::Insert {
key: self.encrypt_key(key),
value: self.encrypt_value(value),
},
Event::Remove { key } => Event::Remove {
key: self.encrypt_key(key),
},
}
}
fn decrypt_event(&self, event: Event) -> Event {
match event {
Event::Insert { key, value } => Event::Insert {
key: self.decrypt_key(key),
value: self.decrypt_value(value),
},
Event::Remove { key } => Event::Remove {
key: self.decrypt_key(key),
},
}
}
fn encrypt_batch(&self, batch: Batch) -> sled::Batch {
let mut encrypted = sled::Batch::default();
for event in batch.events {
match self.encrypt_event(event) {
Event::Insert { key, value } => encrypted.insert(key, value),
Event::Remove { key } => encrypted.remove(key),
}
}
encrypted
}
}
impl<T> Encryption for T
where
T: ops::Deref,
T::Target: Encryption,
{
fn encrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec {
self.deref().encrypt(data, mode)
}
fn decrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec {
self.deref().decrypt(data, mode)
}
}
impl<C> Encryption for EncryptionCipher<C>
where
C: StreamCipher + NewCipher,
{
fn encrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec {
self.apply_to_data(data, mode)
}
fn decrypt_ivec(&self, data: IVec, mode: EncryptionMode) -> IVec {
self.apply_to_data(data, mode)
}
}
#[derive(Debug, Clone)]
pub struct Tree<E> {
inner: sled::Tree,
encryption: Arc<E>,
}
impl<E> Tree<E> {
pub(crate) fn new(inner: sled::Tree, encryption: Arc<E>) -> Self {
Self { inner, encryption }
}
}
#[derive(Debug, Clone)]
pub struct Db<E> {
inner: sled::Db,
tree: Tree<E>,
encryption: Arc<E>,
}
impl<E> Db<E> {
pub(crate) fn new(inner: sled::Db, encryption: Arc<E>) -> Self {
let tree = Tree::new(sled::Tree::clone(&inner), encryption.clone());
Self {
inner,
tree,
encryption,
}
}
}
impl<E> ops::Deref for Db<E> {
type Target = Tree<E>;
fn deref(&self) -> &Tree<E> {
&self.tree
}
}
#[derive(Debug, Clone)]
pub struct Config<E> {
inner: sled::Config,
encryption: Arc<E>,
}
macro_rules! config_fn {
($name:ident, $t:ty) => {
pub fn $name(self, to: $t) -> Self {
Self {
inner: self.inner.$name(to),
encryption: self.encryption,
}
}
};
}
impl<E> Config<E>
where
E: Encryption,
{
pub fn new(encryption: E) -> Self {
Self {
inner: sled::Config::new(),
encryption: Arc::new(encryption),
}
}
pub fn path<P: AsRef<Path>>(self, path: P) -> Self {
Self {
inner: self.inner.path(path),
encryption: self.encryption,
}
}
pub fn open(&self) -> Result<Db<E>> {
self.inner
.open()
.map(move |db| Db::new(db, self.encryption.clone()))
}
config_fn!(cache_capacity, u64);
config_fn!(mode, sled::Mode);
config_fn!(use_compression, bool);
config_fn!(compression_factor, i32);
config_fn!(temporary, bool);
config_fn!(create_new, bool);
config_fn!(print_profile_on_drop, bool);
}
#[derive(Debug, Clone, Default)]
pub struct Batch {
events: Vec<Event>,
}
impl Batch {
pub fn insert<K, V>(&mut self, key: K, value: V)
where
K: Into<IVec>,
V: Into<IVec>,
{
self.events.push(Event::Insert {
key: key.into(),
value: value.into(),
})
}
pub fn remove<K>(&mut self, key: K)
where
K: Into<IVec>,
{
self.events.push(Event::Remove { key: key.into() })
}
}
impl<E> Db<E>
where
E: Encryption,
{
pub fn open_tree<V: AsRef<[u8]>>(&self, name: V) -> Result<Tree<E>> {
self.inner
.open_tree(self.encryption.encrypt_tree_name(name.as_ref()))
.map(|tree| Tree::new(tree, self.encryption.clone()))
}
pub fn drop_tree<V: AsRef<[u8]>>(&self, name: V) -> Result<bool> {
self.inner
.drop_tree(self.encryption.encrypt_tree_name(name.as_ref()))
}
pub fn tree_names(&self) -> Vec<IVec> {
self.inner
.tree_names()
.into_iter()
.map(|name| self.encryption.decrypt_tree_name(name))
.collect()
}
#[inline]
pub fn was_recovered(&self) -> bool {
self.inner.was_recovered()
}
#[inline]
pub fn generate_id(&self) -> Result<u64> {
self.inner.generate_id()
}
#[inline]
pub fn checksum(&self) -> Result<u32> {
self.inner.checksum()
}
#[inline]
pub fn size_on_disk(&self) -> Result<u64> {
self.inner.size_on_disk()
}
// TODO implement export and import
}
pub struct Iter<E> {
inner: sled::Iter,
encryption: Arc<E>,
}
impl<E> Iter<E> {
pub(crate) fn new(inner: sled::Iter, encryption: Arc<E>) -> Self {
Self { inner, encryption }
}
}
impl<E> Iter<E>
where
E: Encryption + Send + Sync,
{
pub fn keys(self) -> impl DoubleEndedIterator<Item = Result<IVec>> + Send + Sync {
let encryption = self.encryption;
self.inner
.keys()
.map(move |key_res| key_res.map(|key| encryption.decrypt_key(key)))
}
pub fn values(self) -> impl DoubleEndedIterator<Item = Result<IVec>> + Send + Sync {
let encryption = self.encryption;
self.inner
.values()
.map(move |key_res| key_res.map(|key| encryption.decrypt_value(key)))
}
}
impl<E> Iterator for Iter<E>
where
E: Encryption,
{
type Item = Result<(IVec, IVec)>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|res| {
res.map(|(k, v)| {
(
self.encryption.decrypt_key(k),
self.encryption.decrypt_value(v),
)
})
})
}
}
impl<E> DoubleEndedIterator for Iter<E>
where
E: Encryption,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|res| {
res.map(|(k, v)| {
(
self.encryption.decrypt_key(k),
self.encryption.decrypt_value(v),
)
})
})
}
}
pub struct Subscriber<E> {
inner: sled::Subscriber,
encryption: Arc<E>,
}
impl<E> Subscriber<E> {
pub(crate) fn new(inner: sled::Subscriber, encryption: Arc<E>) -> Self {
Self { inner, encryption }
}
fn pin_get_inner(self: Pin<&mut Self>) -> Pin<&mut sled::Subscriber> {
unsafe { self.map_unchecked_mut(|s| &mut s.inner) }
}
}
impl<E> Subscriber<E>
where
E: Encryption,
{
pub fn next_timeout(&mut self, timeout: Duration) -> Result<Event, RecvTimeoutError> {
self.inner
.next_timeout(timeout)
.map(|event| self.encryption.decrypt_event(event))
}
}
impl<E> Future for Subscriber<E>
where
E: Encryption,
{
type Output = Option<Event>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let encryption = self.encryption.clone();
self.pin_get_inner()
.poll(cx)
.map(|event| event.map(|event| encryption.decrypt_event(event)))
}
}
impl<E> Iterator for Subscriber<E>
where
E: Encryption,
{
type Item = Event;
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
.map(|event| self.encryption.decrypt_event(event))
}
}
impl<E> Tree<E>
where
E: Encryption,
{
pub fn insert<K, V>(&self, key: K, value: V) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
V: Into<IVec>,
{
self.encryption.decrypt_value_result(self.inner.insert(
self.encryption.encrypt_key(key.as_ref()),
self.encryption.encrypt_value(value),
))
}
pub fn get<K: AsRef<[u8]>>(&self, key: K) -> Result<Option<IVec>> {
self.encryption
.decrypt_value_result(self.inner.get(self.encryption.encrypt_key(key.as_ref())))
}
pub fn remove<K: AsRef<[u8]>>(&self, key: K) -> Result<Option<IVec>> {
self.encryption
.decrypt_value_result(self.inner.remove(self.encryption.encrypt_key(key.as_ref())))
}
pub fn transaction<F, A, Error>(&self, f: F) -> transaction::TransactionResult<A, Error>
where
F: Fn(
&transaction::TransactionalTree<E>,
) -> transaction::ConflictableTransactionResult<A, Error>,
{
self.inner.transaction(|tree| {
f(&transaction::TransactionalTree::new(
tree.clone(),
self.encryption.clone(),
))
})
}
pub fn watch_prefix<P: AsRef<[u8]>>(&self, prefix: P) -> Subscriber<E> {
Subscriber::new(
self.inner
.watch_prefix(self.encryption.encrypt_key(prefix.as_ref())),
self.encryption.clone(),
)
}
pub fn apply_batch(&self, batch: Batch) -> Result<()> {
self.inner.apply_batch(self.encryption.encrypt_batch(batch))
}
pub fn compare_and_swap<K, OV, NV>(
&self,
key: K,
old: Option<OV>,
new: Option<NV>,
) -> Result<Result<(), CompareAndSwapError>>
where
K: AsRef<[u8]>,
OV: AsRef<[u8]>,
NV: Into<IVec>,
{
self.inner
.compare_and_swap(
self.encryption.encrypt_key(key.as_ref()),
old.map(|val| self.encryption.encrypt_value(val.as_ref())),
new.map(|val| self.encryption.encrypt_value(val)),
)
.map(|res| {
res.map_err(|cas| CompareAndSwapError {
current: cas.current.map(|v| self.encryption.decrypt_value(v)),
proposed: cas.proposed.map(|v| self.encryption.decrypt_value(v)),
})
})
}
pub fn update_and_fetch<K, V, F>(&self, key: K, mut f: F) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
F: FnMut(Option<IVec>) -> Option<V>,
V: Into<IVec>,
{
let new_f = move |old: Option<&[u8]>| {
f(old.map(|val| self.encryption.decrypt_value(val.as_ref())))
.map(|val| self.encryption.encrypt_value(val))
};
self.encryption.decrypt_value_result(
self.inner
.update_and_fetch(self.encryption.encrypt_key(key.as_ref()), new_f),
)
}
pub fn fetch_and_update<K, V, F>(&self, key: K, mut f: F) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
F: FnMut(Option<IVec>) -> Option<V>,
V: Into<IVec>,
{
let new_f = move |old: Option<&[u8]>| {
f(old.map(|val| self.encryption.decrypt_value(val.as_ref())))
.map(|val| self.encryption.encrypt_value(val))
};
self.encryption.decrypt_value_result(
self.inner
.fetch_and_update(self.encryption.encrypt_key(key.as_ref()), new_f),
)
}
#[inline]
pub fn flush(&self) -> Result<usize> {
self.inner.flush()
}
#[inline]
pub async fn flush_async(&self) -> Result<usize> {
self.inner.flush_async().await
}
pub fn contains_key<K: AsRef<[u8]>>(&self, key: K) -> Result<bool> {
self.inner
.contains_key(self.encryption.encrypt_key(key.as_ref()))
}
pub fn get_lt<K>(&self, key: K) -> Result<Option<(IVec, IVec)>>
where
K: AsRef<[u8]>,
{
self.encryption
.decrypt_key_value_result(self.inner.get_lt(self.encryption.encrypt_key(key.as_ref())))
}
pub fn get_gt<K>(&self, key: K) -> Result<Option<(IVec, IVec)>>
where
K: AsRef<[u8]>,
{
self.encryption
.decrypt_key_value_result(self.inner.get_gt(self.encryption.encrypt_key(key.as_ref())))
}
pub fn first(&self) -> Result<Option<(IVec, IVec)>> {
self.encryption.decrypt_key_value_result(self.inner.first())
}
pub fn last(&self) -> Result<Option<(IVec, IVec)>> {
self.encryption.decrypt_key_value_result(self.inner.last())
}
pub fn pop_min(&self) -> Result<Option<(IVec, IVec)>> {
self.encryption
.decrypt_key_value_result(self.inner.pop_min())
}
pub fn pop_max(&self) -> Result<Option<(IVec, IVec)>> {
self.encryption
.decrypt_key_value_result(self.inner.pop_max())
}
pub fn iter(&self) -> Iter<E> {
Iter::new(self.inner.iter(), self.encryption.clone())
}
pub fn range<K, R>(&self, range: R) -> Iter<E>
where
K: AsRef<[u8]>,
R: ops::RangeBounds<K>,
{
let encrypt_bound = |bound: ops::Bound<&K>| -> ops::Bound<IVec> {
match bound {
ops::Bound::Unbounded => ops::Bound::Unbounded,
ops::Bound::Included(x) => {
ops::Bound::Included(self.encryption.encrypt_key(x.as_ref()))
}
ops::Bound::Excluded(x) => {
ops::Bound::Excluded(self.encryption.encrypt_key(x.as_ref()))
}
}
};
let range = (
encrypt_bound(range.start_bound()),
encrypt_bound(range.end_bound()),
);
Iter::new(self.inner.range(range), self.encryption.clone())
}
pub fn scan_prefix<P>(&self, prefix: P) -> Iter<E>
where
P: AsRef<[u8]>,
{
Iter::new(
self.inner
.scan_prefix(self.encryption.encrypt_key(prefix.as_ref())),
self.encryption.clone(),
)
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[inline]
pub fn clear(&self) -> Result<()> {
self.inner.clear()
}
pub fn name(&self) -> IVec {
self.encryption.decrypt_tree_name(self.inner.name())
}
#[inline]
pub fn checksum(&self) -> Result<u32> {
self.inner.checksum()
}
}
impl<E> Tree<E>
where
E: Encryption + 'static,
{
pub fn merge<K, V>(&self, key: K, value: V) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.encryption.decrypt_value_result(self.inner.merge(
self.encryption.encrypt_key(key.as_ref()),
self.encryption.encrypt_value(value.as_ref()),
))
}
pub fn set_merge_operator(&self, merge_operator: impl sled::MergeOperator + 'static) {
let encryption = self.encryption.clone();
let new_operator = move |key: &[u8], old: Option<&[u8]>, merged: &[u8]| {
merge_operator(
&encryption.decrypt_key(key.as_ref()),
old.map(|v| encryption.decrypt_value(v.as_ref())).as_deref(),
&encryption.decrypt_value(merged.as_ref()),
)
.map(|v| encryption.encrypt_value(v).to_vec())
};
self.inner.set_merge_operator(new_operator);
}
}
pub mod transaction {
use super::*;
pub use sled::transaction::{
abort, ConflictableTransactionError, ConflictableTransactionResult, TransactionError,
TransactionResult, UnabortableTransactionError,
};
pub struct TransactionalTree<E> {
inner: sled::transaction::TransactionalTree,
encryption: Arc<E>,
}
impl<E> TransactionalTree<E>
where
E: Encryption,
{
pub(crate) fn new(inner: sled::transaction::TransactionalTree, encryption: Arc<E>) -> Self {
Self { inner, encryption }
}
pub fn insert<K, V>(
&self,
key: K,
value: V,
) -> Result<Option<IVec>, UnabortableTransactionError>
where
K: AsRef<[u8]>,
V: Into<IVec>,
{
self.encryption.decrypt_value_result(self.inner.insert(
self.encryption.encrypt_key(key.as_ref()),
self.encryption.encrypt_value(value),
))
}
pub fn get<K: AsRef<[u8]>>(
&self,
key: K,
) -> Result<Option<IVec>, UnabortableTransactionError> {
self.encryption
.decrypt_value_result(self.inner.get(self.encryption.encrypt_key(key.as_ref())))
}
pub fn remove<K: AsRef<[u8]>>(
&self,
key: K,
) -> Result<Option<IVec>, UnabortableTransactionError> {
self.encryption
.decrypt_value_result(self.inner.remove(self.encryption.encrypt_key(key.as_ref())))
}
pub fn apply_batch(&self, batch: &Batch) -> Result<(), UnabortableTransactionError> {
self.inner
.apply_batch(&self.encryption.encrypt_batch(batch.clone()))
}
#[inline]
pub fn flush(&self) {
self.inner.flush()
}
#[inline]
pub fn generate_id(&self) -> Result<u64> {
self.inner.generate_id()
}
}
}
pub fn open<P: AsRef<Path>, E: Encryption>(path: P, encryption: E) -> Result<Db<E>> {
sled::open(path).map(|db| Db::new(db, Arc::new(encryption)))
}
#[cfg(test)]
mod tests {
use super::*;
use chacha20::ChaCha20;
type TestCipher = EncryptionCipher<ChaCha20>;
type TestDb = Db<TestCipher>;
const ENCRYPTION_KEY: &[u8] = b"an example very very secret key.";
const ENCRYPTION_NONCE: &[u8] = b"secret nonce";
fn test_cipher(mode: EncryptionMode) -> TestCipher {
EncryptionCipher::new_from_slices(ENCRYPTION_KEY, ENCRYPTION_NONCE, mode).unwrap()
}
fn temp_db(mode: EncryptionMode) -> TestDb {
println!("opening test db with: {:?}", mode);
Config::new(test_cipher(mode))
.temporary(true)
.open()
.unwrap()
}
fn for_all_dbs<F>(f: F) -> Result<()>
where
F: Fn(TestDb) -> Result<()>,
{
for mode in &[
EncryptionMode::empty(),
EncryptionMode::KEY,
EncryptionMode::VALUE,
EncryptionMode::TREE_NAME,
EncryptionMode::KEY | EncryptionMode::VALUE,
EncryptionMode::KEY | EncryptionMode::TREE_NAME,
EncryptionMode::VALUE | EncryptionMode::TREE_NAME,
EncryptionMode::KEY | EncryptionMode::VALUE | EncryptionMode::TREE_NAME,
] {
f(temp_db(*mode))?
}
Ok(())
}
fn str_res(res: Result<Option<IVec>>) -> Result<Option<String>> {
res.map(|val| val.map(|val| String::from_utf8_lossy(&val).to_string()))
}
#[test]
fn insert() -> Result<()> {
for_all_dbs(|db| {
let tree = db.open_tree("hello").unwrap();
assert!(!tree.contains_key("hello").unwrap());
tree.insert("hello", "hi").unwrap();
assert!(tree.contains_key("hello").unwrap());
assert_eq!(Ok(Some("hi".to_string())), str_res(tree.get("hello")));
tree.remove("hello").unwrap();
assert!(!tree.contains_key("hello").unwrap());
assert_eq!(Ok(None), str_res(tree.get("hello")));
Ok(())
})
}
fn u64_to_ivec(number: u64) -> IVec {
IVec::from(number.to_be_bytes().to_vec())
}
fn increment(old: Option<IVec>) -> Option<Vec<u8>> {
let number = match old {
Some(bytes) => {
let mut array = [0; 8];
array.copy_from_slice(&bytes);
let number = u64::from_be_bytes(array);
number + 1
}
None => 0,
};
Some(number.to_be_bytes().to_vec())
}
#[test]
fn update_and_fetch() -> Result<()> {
for_all_dbs(|db| {
let zero = u64_to_ivec(0);
let one = u64_to_ivec(1);
let two = u64_to_ivec(2);
let three = u64_to_ivec(3);
assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(zero)));
assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(one)));
assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(two)));
assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(three)));
Ok(())
})
}
#[test]
fn fetch_and_update() -> Result<()> {
for_all_dbs(|db| {
let zero = u64_to_ivec(0);
let one = u64_to_ivec(1);
let two = u64_to_ivec(2);
assert_eq!(db.fetch_and_update("counter", increment), Ok(None));
assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(zero)));
assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(one)));
assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(two)));
Ok(())
})
}
#[test]
fn merge() -> Result<()> {
fn concatenate_merge(
_key: &[u8], // the key being merged
old_value: Option<&[u8]>, // the previous value, if one existed
merged_bytes: &[u8], // the new bytes being merged in
) -> Option<Vec<u8>> {
// set the new value, return None to delete
let mut ret = old_value.map(|ov| ov.to_vec()).unwrap_or_else(|| vec![]);
ret.extend_from_slice(merged_bytes);
Some(ret)
}
for_all_dbs(|tree| {
tree.set_merge_operator(concatenate_merge);
let k = b"k1";
tree.insert(k, vec![0]).unwrap();
tree.merge(k, vec![1]).unwrap();
tree.merge(k, vec![2]).unwrap();
assert_eq!(tree.get(k), Ok(Some(IVec::from(vec![0, 1, 2]))));
// Replace previously merged data. The merge function will not be called.
tree.insert(k, vec![3]).unwrap();
assert_eq!(tree.get(k), Ok(Some(IVec::from(vec![3]))));
// Merges on non-present values will cause the merge function to be called
// with `old_value == None`. If the merge function returns something (which it
// does, in this case) a new value will be inserted.
tree.remove(k).unwrap();
tree.merge(k, vec![4]).unwrap();
assert_eq!(tree.get(k), Ok(Some(IVec::from(vec![4]))));
Ok(())
})
}
#[test]
fn batch() -> Result<()> {
for_all_dbs(|db| {
let mut batch = Batch::default();
batch.insert("key_a", "val_a");
batch.insert("key_b", "val_b");
batch.insert("key_c", "val_c");
batch.remove("key_0");
db.apply_batch(batch)?;
Ok(())
})
}
#[test]
fn transaction_err() -> Result<()> {
#[derive(Debug, PartialEq)]
struct MyBullshitError;
for_all_dbs(|db| {
// Use write-only transactions as a writebatch:
let res = db
.transaction(|tx_db| {
tx_db.insert(b"k1", b"cats")?;
tx_db.insert(b"k2", b"dogs")?;
// aborting will cause all writes to roll-back.
if true {
transaction::abort(MyBullshitError)?;
}
Ok(42)
})
.unwrap_err();
assert_eq!(res, transaction::TransactionError::Abort(MyBullshitError));
assert_eq!(db.get(b"k1")?, None);
assert_eq!(db.get(b"k2")?, None);
Ok(())
})
}
#[test]
fn iter() -> Result<()> {
for_all_dbs(|db| {
db.insert(&[1], vec![10])?;
db.insert(&[2], vec![20])?;
db.insert(&[3], vec![30])?;
let mut out = db.iter().collect::<Vec<Result<(IVec, IVec)>>>();
out.sort_by_key(|res| res.clone().unwrap());
assert_eq!(
&out,
&[
Ok((IVec::from(&[1]), IVec::from(&[10]))),
Ok((IVec::from(&[2]), IVec::from(&[20]))),
Ok((IVec::from(&[3]), IVec::from(&[30])))
]
);
Ok(())
})
}
#[test]
fn subscribe() -> Result<()> {
for_all_dbs(|db| {
let subscriber = db.watch_prefix(vec![]);
let _ = std::thread::spawn(move || db.insert(vec![0], vec![1]));
for event in subscriber.take(1) {
match event {
sled::Event::Insert { key, .. } => assert_eq!(key.as_ref(), &[0]),
sled::Event::Remove { .. } => {}
}
}
Ok(())
})
}
}
|
use std::collections::BTreeMap;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
#[derive(Default)]
pub struct Crate {
pub include_prefix: Option<PathBuf>,
pub links: Option<OsString>,
pub header_dirs: Vec<HeaderDir>,
}
pub struct HeaderDir {
pub exported: bool,
pub path: PathBuf,
}
impl Crate {
pub fn print_to_cargo(&self) {
if let Some(include_prefix) = &self.include_prefix {
println!(
"cargo:CXXBRIDGE_PREFIX={}",
include_prefix.to_string_lossy(),
);
}
if let Some(links) = &self.links {
println!("cargo:CXXBRIDGE_LINKS={}", links.to_string_lossy());
}
for (i, header_dir) in self.header_dirs.iter().enumerate() {
if header_dir.exported {
println!(
"cargo:CXXBRIDGE_DIR{}={}",
i,
header_dir.path.to_string_lossy(),
);
}
}
}
}
pub fn direct_dependencies() -> Vec<Crate> {
let mut crates: BTreeMap<String, Crate> = BTreeMap::new();
let mut exported_header_dirs: BTreeMap<String, Vec<(usize, PathBuf)>> = BTreeMap::new();
// Only variables set from a build script of direct dependencies are
// observable. That's exactly what we want! Your crate needs to declare a
// direct dependency on the other crate in order to be able to #include its
// headers.
//
// Also, they're only observable if the dependency's manifest contains a
// `links` key. This is important because Cargo imposes no ordering on the
// execution of build scripts without a `links` key. When exposing a
// generated header for the current crate to #include, we need to be sure
// the dependency's build script has already executed and emitted that
// generated header.
//
// References:
// - https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key
// - https://doc.rust-lang.org/cargo/reference/build-script-examples.html#using-another-sys-crate
for (k, v) in env::vars_os() {
let mut k = k.to_string_lossy().into_owned();
if !k.starts_with("DEP_") {
continue;
}
if k.ends_with("_CXXBRIDGE_PREFIX") {
k.truncate(k.len() - "_CXXBRIDGE_PREFIX".len());
crates.entry(k).or_default().include_prefix = Some(PathBuf::from(v));
continue;
}
if k.ends_with("_CXXBRIDGE_LINKS") {
k.truncate(k.len() - "_CXXBRIDGE_LINKS".len());
crates.entry(k).or_default().links = Some(v);
continue;
}
let without_counter = k.trim_end_matches(|ch: char| ch.is_ascii_digit());
let counter_len = k.len() - without_counter.len();
if counter_len == 0 || !without_counter.ends_with("_CXXBRIDGE_DIR") {
continue;
}
let sort_key = k[k.len() - counter_len..]
.parse::<usize>()
.unwrap_or(usize::MAX);
k.truncate(k.len() - counter_len - "_CXXBRIDGE_DIR".len());
exported_header_dirs
.entry(k)
.or_default()
.push((sort_key, PathBuf::from(v)));
}
for (k, mut dirs) in exported_header_dirs {
dirs.sort_by_key(|(sort_key, _dir)| *sort_key);
crates
.entry(k)
.or_default()
.header_dirs
.extend(dirs.into_iter().map(|(_sort_key, dir)| HeaderDir {
exported: true,
path: dir,
}));
}
crates.into_iter().map(|entry| entry.1).collect()
}
|
mod codec;
mod from_resp;
mod resp_value;
pub use self::codec::{RespCodec, RespMsgError};
pub use self::from_resp::{
FromResp,
RespStringConvertError,
RespIntConvertError,
RespBytesConvertError,
RespVecConvertError,
};
pub use self::resp_value::RespValue;
|
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
ChronError(#[from] cron_clock::error::Error),
}
|
use super::LoadArgs;
use crate::{BoxFuture, Entity, Error, GetMut, Result};
pub trait LoadOne<E: Entity>: Send + Sync {
fn load_one_with_args<'a>(
&'a self,
k: &'a E::Key,
args: LoadArgs,
) -> BoxFuture<'a, Result<Option<E>>>;
fn load_one<'a>(&'a self, k: &'a E::Key) -> BoxFuture<'a, Result<Option<E>>> {
self.load_one_with_args(k, LoadArgs::default())
}
fn load_one_ok<'a>(&'a self, k: &'a E::Key) -> BoxFuture<'a, Result<E>> {
Box::pin(async move { self.load_one(k).await?.ok_or(Error::EntityNotFound) })
}
}
#[doc(hidden)]
#[derive(Default)]
pub struct LoadDoNothing;
impl<T> Extend<T> for LoadDoNothing {
fn extend<I: IntoIterator<Item = T>>(&mut self, _iter: I) {}
}
#[doc(hidden)]
#[derive(Default)]
pub struct LoadNothing;
impl<T> Extend<T> for LoadNothing {
fn extend<I: IntoIterator<Item = T>>(&mut self, _iter: I) {}
}
impl<E: Entity> GetMut<E> for LoadNothing
where
E::Key: PartialEq,
{
fn get_mut(&mut self, _k: &E::Key) -> Option<&mut E> {
None
}
}
#[doc(hidden)]
pub struct LoadOneInternal<E: Entity>(Option<(E::Key, E)>);
impl<E: Entity> LoadOneInternal<E> {
pub fn into_inner(self) -> Option<E> {
self.0.map(|t| t.1)
}
}
impl<E: Entity> Default for LoadOneInternal<E> {
fn default() -> Self {
Self(None)
}
}
impl<E: Entity> Extend<(E::Key, E)> for LoadOneInternal<E> {
fn extend<I: IntoIterator<Item = (E::Key, E)>>(&mut self, iter: I) {
self.0 = iter.into_iter().next();
}
}
impl<E: Entity> GetMut<E> for LoadOneInternal<E>
where
E::Key: PartialEq,
{
fn get_mut(&mut self, k: &E::Key) -> Option<&mut E> {
self.0.as_mut().filter(|t| &t.0 == k).map(|t| &mut t.1)
}
}
|
// Copyright 2015 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
struct PrivateKey {
bytes: [u8; SCALAR_MAX_BYTES],
}
const INVALID_ZERO_PRIVATE_KEY_BYTES: [u8; SCALAR_MAX_BYTES] =
[0u8; SCALAR_MAX_BYTES];
// XXX: Not correct for x32 ABIs.
#[cfg(target_pointer_width = "64")] type Limb = u64;
#[cfg(target_pointer_width = "32")] type Limb = u32;
// When the `no_heap` feature isn't being used, P-384 has the largest field
// element size.
#[cfg(not(feature = "no_heap"))]
const ELEM_MAX_BITS: usize = 384;
// When the `no_heap` feature is used, P-384 and P-256 aren't available, so
// X25519 has the largest field element size.
#[cfg(feature = "no_heap")]
const ELEM_MAX_BITS: usize = 256;
const ELEM_MAX_BYTES: usize = (ELEM_MAX_BITS + 7) / 8;
const SCALAR_MAX_BYTES: usize = ELEM_MAX_BYTES;
/// The maximum length, in bytes, of an encoded public key. Note that the value
/// depends on which algorithms are enabled (e.g. whether the `no_heap` feature
/// is activated).
pub const PUBLIC_KEY_MAX_LEN: usize = ELEM_MAX_BYTES;
#[allow(non_camel_case_types)]
#[cfg(not(feature = "no_heap"))]
enum EC_GROUP { }
#[cfg(not(feature = "no_heap"))]
extern {
fn EC_GROUP_P256() -> *const EC_GROUP;
fn EC_GROUP_P384() -> *const EC_GROUP;
}
pub mod ecdh;
#[cfg(not(feature = "no_heap"))]
pub mod ecdsa;
pub mod eddsa;
#[cfg(not(feature = "no_heap"))]
pub mod nist_public;
|
extern crate gotham;
#[macro_use]
extern crate gotham_derive;
#[macro_use]
extern crate hyper;
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
extern crate mime;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
use hyper::StatusCode;
use std::env;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use ipc_channel::ipc;
use gotham::http::response::create_response;
use gotham::router::Router;
use gotham::router::builder::*;
use gotham::state::State;
#[derive(Serialize, Deserialize, Debug)]
pub enum Message {
GetTaskCount,
AddReviewRequest,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum Response {
Booted {
port: SocketAddr,
sender: ipc::IpcSender<Message>,
},
TaskCountResponse(usize),
}
lazy_static! {
static ref ADDR: SocketAddr = get_open_port();
}
header! { (XPollInterval, "X-Poll-Interval") => [u64] }
fn notifications(state: State) -> (State, hyper::Response) {
let count = REVIEW_REQUEST_COUNT.load(Ordering::Relaxed);
let pull_requests: Vec<serde_json::Value> = (0..count)
.map(|i| {
let pr_url = format!("http://{}/github/pull_requests/{}", &*ADDR, i);
json!({
"reason": "review_requested",
"subject": {
"title": "Some important PR",
"url": pr_url,
"type": "PullRequest"
},
"repository": {
"name": "reviewist",
}
})
})
.collect();
let response_body = serde_json::to_vec(&serde_json::Value::Array(pull_requests)).unwrap();
let mut res = create_response(&state, StatusCode::Ok, Some((response_body, mime::APPLICATION_JSON)));
res.headers_mut().set(XPollInterval(1));
(state, res)
}
fn get_pull_request(state: State) -> (State, hyper::Response) {
let response_body = {
let PullRequestParams { id, .. } = state.borrow();
let response_json = json!({
"number": id,
"title": "Some important PR",
"html_url": "https://example.com",
"created_at": "2018-01-01T00:00:00Z",
"merged_at": null,
"closed_at": null,
"base": {
"repo": {
"name": "reviewist",
},
},
});
serde_json::to_vec(&response_json).unwrap()
};
let res = create_response(&state, StatusCode::Ok, Some((response_body, mime::APPLICATION_JSON)));
(state, res)
}
#[derive(Deserialize, StateData, StaticResponseExtender)]
struct PullRequestParams {
id: i32,
}
lazy_static! {
static ref TASK_COUNT: AtomicUsize = AtomicUsize::new(0);
static ref REVIEW_REQUEST_COUNT: AtomicUsize = AtomicUsize::new(0);
}
fn create_task(state: State) -> (State, hyper::Response) {
TASK_COUNT.fetch_add(1, Ordering::Relaxed);
let res = create_response(&state, StatusCode::Ok, Some((b"OK".to_vec(), mime::TEXT_PLAIN)));
(state, res)
}
fn router() -> Router {
build_simple_router(|route| {
route.get("/github/notifications").to(notifications);
route
.get("/github/pull_requests/:id")
.with_path_extractor::<PullRequestParams>()
.to(get_pull_request);
route.post("/todoist/API/v8/tasks").to(create_task);
})
}
pub fn run() {
bootstrap_channels();
gotham::start(ADDR.clone(), router());
}
fn bootstrap_channels() -> Option<()> {
let response_sender = build_response_sender()?;
let message_sender = build_message_sender(response_sender.clone())?;
response_sender
.send(Response::Booted {
port: ADDR.clone(),
sender: message_sender,
})
.unwrap();
Some(())
}
fn build_message_sender(response_sender: ipc::IpcSender<Response>) -> Option<ipc::IpcSender<Message>> {
let (message_sender, message_receiver) = ipc::channel().ok()?;
thread::spawn(move || process_messages(message_receiver, response_sender));
Some(message_sender)
}
fn process_messages(receiver: ipc::IpcReceiver<Message>, sender: ipc::IpcSender<Response>) {
while let Ok(message) = receiver.recv() {
match message {
Message::GetTaskCount => {
let value = TASK_COUNT.load(Ordering::Relaxed);
sender.send(Response::TaskCountResponse(value)).ok();
}
Message::AddReviewRequest => {
REVIEW_REQUEST_COUNT.fetch_add(1, Ordering::Relaxed);
}
}
}
}
fn build_response_sender() -> Option<ipc::IpcSender<Response>> {
let server_path: String = env::args().skip(1).next()?;
ipc::IpcSender::connect(server_path).ok()
}
fn get_open_port() -> SocketAddr {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
return addr;
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::Error;
use fidl::endpoints::create_proxy;
use fidl_fuchsia_stash::*;
use futures::lock::Mutex;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::sync::Arc;
const SETTINGS_PREFIX: &str = "settings";
/// Stores device level settings in persistent storage.
/// User level settings should not use this.
pub struct DeviceStorage<T> {
current_data: Option<T>,
stash_proxy: StoreAccessorProxy,
}
/// Structs that can be stored in device storage should derive the Serialize, Deserialize, and
/// Copy traits, as well as provide constants.
/// KEY should be unique the struct, usually the name of the struct itself.
/// DEFAULT_VALUE will be the value returned when nothing has yet been stored.
///
/// Anything that implements this should not introduce breaking changes with the same key.
/// Clients that want to make a breaking change should create a new structure with a new key and
/// implement conversion/cleanup logic. Adding optional fields to a struct is not breaking, but
/// removing fields, renaming fields, or adding non-optional fields are.
pub trait DeviceStorageCompatible: Serialize + DeserializeOwned + Copy + PartialEq {
const DEFAULT_VALUE: Self;
const KEY: &'static str;
}
impl<T: DeviceStorageCompatible> DeviceStorage<T> {
pub fn write(&mut self, new_value: T) -> Result<(), Error> {
if self.current_data != Some(new_value) {
self.current_data = Some(new_value);
let mut serialized = Value::Stringval(serde_json::to_string(&new_value).unwrap());
self.stash_proxy.set_value(&prefixed(T::KEY), &mut serialized)?;
self.stash_proxy.commit()?;
}
Ok(())
}
/// Gets the latest value cached locally, or loads the value from storage.
/// Doesn't support multiple concurrent callers of the same struct.
pub async fn get(&mut self) -> T {
if let None = self.current_data {
if let Some(stash_value) = self.stash_proxy.get_value(&prefixed(T::KEY)).await.unwrap()
{
if let Value::Stringval(string_value) = &*stash_value {
self.current_data = Some(serde_json::from_str(&string_value).unwrap());
} else {
panic!("Unexpected type for key found in stash");
}
} else {
self.current_data = Some(T::DEFAULT_VALUE);
}
}
if let Some(curent_value) = self.current_data {
curent_value
} else {
panic!("Should never have no value");
}
}
}
pub trait DeviceStorageFactory {
fn get_store<T: DeviceStorageCompatible>(&self) -> Arc<Mutex<DeviceStorage<T>>>;
}
/// Factory that vends out storage for individual structs.
pub struct StashDeviceStorageFactory {
store: StoreProxy,
}
impl StashDeviceStorageFactory {
pub fn create(identity: &str, store: StoreProxy) -> StashDeviceStorageFactory {
let result = store.identify(identity);
match result {
Ok(_) => {}
Err(_) => {
panic!("Was not able to identify with stash");
}
}
StashDeviceStorageFactory { store: store }
}
}
impl DeviceStorageFactory for StashDeviceStorageFactory {
/// Currently, this doesn't support more than one instance of the same struct.
fn get_store<T: DeviceStorageCompatible>(&self) -> Arc<Mutex<DeviceStorage<T>>> {
let (accessor_proxy, server_end) = create_proxy().unwrap();
self.store.create_accessor(false, server_end).unwrap();
Arc::new(Mutex::new(DeviceStorage { stash_proxy: accessor_proxy, current_data: None }))
}
}
fn prefixed(input_string: &str) -> String {
format!("{}_{}", SETTINGS_PREFIX, input_string)
}
#[cfg(test)]
pub mod testing {
use super::*;
use fidl::encoding::OutOfLine;
use fuchsia_async as fasync;
use futures::prelude::*;
/// Storage that does not write to disk, for testing.
/// Only supports a single key/value pair
pub struct InMemoryStorageFactory {}
impl InMemoryStorageFactory {
pub fn create() -> InMemoryStorageFactory {
InMemoryStorageFactory {}
}
}
impl DeviceStorageFactory for InMemoryStorageFactory {
fn get_store<T: DeviceStorageCompatible>(&self) -> Arc<Mutex<DeviceStorage<T>>> {
Arc::new(Mutex::new(DeviceStorage {
stash_proxy: spawn_stash_proxy(),
current_data: None,
}))
}
}
fn spawn_stash_proxy() -> StoreAccessorProxy {
let (stash_proxy, mut stash_stream) =
fidl::endpoints::create_proxy_and_stream::<StoreAccessorMarker>().unwrap();
fasync::spawn(async move {
let mut stored_value: Option<Value> = None;
let mut stored_key: Option<String> = None;
while let Some(req) = stash_stream.try_next().await.unwrap() {
#[allow(unreachable_patterns)]
match req {
StoreAccessorRequest::GetValue { key, responder } => {
if let Some(key_string) = stored_key {
assert_eq!(key, key_string);
}
stored_key = Some(key);
responder.send(stored_value.as_mut().map(OutOfLine)).unwrap();
}
StoreAccessorRequest::SetValue { key, val, control_handle: _ } => {
if let Some(key_string) = stored_key {
assert_eq!(key, key_string);
}
stored_key = Some(key);
stored_value = Some(val);
}
_ => {}
}
}
});
stash_proxy
}
}
#[cfg(test)]
mod tests {
use super::*;
use fidl::encoding::OutOfLine;
use fuchsia_async as fasync;
use futures::prelude::*;
use serde_derive::{Deserialize, Serialize};
const VALUE0: i32 = 3;
const VALUE1: i32 = 33;
const VALUE2: i32 = 128;
#[derive(PartialEq, Clone, Copy, Serialize, Deserialize, Debug)]
struct TestStruct {
value: i32,
}
impl DeviceStorageCompatible for TestStruct {
const DEFAULT_VALUE: Self = TestStruct { value: VALUE0 };
const KEY: &'static str = "testkey";
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_get() {
let (stash_proxy, mut stash_stream) =
fidl::endpoints::create_proxy_and_stream::<StoreAccessorMarker>().unwrap();
fasync::spawn(async move {
let value_to_get = TestStruct { value: VALUE1 };
while let Some(req) = stash_stream.try_next().await.unwrap() {
#[allow(unreachable_patterns)]
match req {
StoreAccessorRequest::GetValue { key, responder } => {
assert_eq!(key, "settings_testkey");
let mut response =
Value::Stringval(serde_json::to_string(&value_to_get).unwrap());
responder.send(Some(&mut response).map(OutOfLine)).unwrap();
}
_ => {}
}
}
});
let mut storage: DeviceStorage<TestStruct> =
DeviceStorage { stash_proxy: stash_proxy, current_data: None };
let result = storage.get().await;
assert_eq!(result.value, VALUE1);
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_get_default() {
let (stash_proxy, mut stash_stream) =
fidl::endpoints::create_proxy_and_stream::<StoreAccessorMarker>().unwrap();
fasync::spawn(async move {
while let Some(req) = stash_stream.try_next().await.unwrap() {
#[allow(unreachable_patterns)]
match req {
StoreAccessorRequest::GetValue { key: _, responder } => {
responder.send(None.map(OutOfLine)).unwrap();
}
_ => {}
}
}
});
let mut storage: DeviceStorage<TestStruct> =
DeviceStorage { stash_proxy: stash_proxy, current_data: None };
let result = storage.get().await;
assert_eq!(result.value, VALUE0);
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_write() {
let (stash_proxy, mut stash_stream) =
fidl::endpoints::create_proxy_and_stream::<StoreAccessorMarker>().unwrap();
let mut storage: DeviceStorage<TestStruct> =
DeviceStorage { stash_proxy: stash_proxy, current_data: None };
storage.write(TestStruct { value: VALUE2 }).expect("writing shouldn't fail");
match stash_stream.next().await.unwrap() {
Ok(StoreAccessorRequest::SetValue { key, val, control_handle: _ }) => {
assert_eq!(key, "settings_testkey");
if let Value::Stringval(string_value) = val {
let input_value: TestStruct = serde_json::from_str(&string_value).unwrap();
assert_eq!(input_value.value, VALUE2);
} else {
panic!("Unexpected type for key found in stash");
}
}
request => panic!("Unexpected request: {:?}", request),
}
match stash_stream.next().await.unwrap() {
Ok(StoreAccessorRequest::Commit { .. }) => {} // expected
request => panic!("Unexpected request: {:?}", request),
}
}
}
|
// bacause variables are in charge of freeing their own resources,
// resources can only have one owner. This also prevents resources
// from being freed more than once. Note that not all variables own
// resources (e.g. references)
// when doing assignments (`let x = y`) or passing function arguments
// by value (`foo(x)`), the ownership of the resources is transferred.
// In Rust-speak, this is known as a move.
//
// After moving resources, the previous owner can no longer be used. This
// avoids creating dangling pointers
fn destroy_box(c: Box<i32>) {
println!("Destroying a box that contains {}", c);
// `c` is destroyed and the memory freed
}
fn main() {
// stack allocated integer
let x = 5u32;
// *Copy* `x` into `y`
let y = x;
// both values can be independently used
println!("x is {}, and y is {}", x, y);
// `a` is a pointer to a heap allocated integer
let a = Box::new(5i32);
println!("a contains: {}", a);
// *Move* `a` into `b`
let b = a;
// the pointer address of `a` is copied (not the data) into `b`
// Both are now pointers to the same heap allocated data, but
// `b` now owns it
// Error! `a` can no longer access the data, because it no longer owns
// the heap memory
// println!("a contains: {}", a);
// this function takes ownership of the heap allocated memory from `b`
destroy_box(b);
// since the heap memory has been freed at this point, this action would
// result in dereferencing freed memory, but it's forbidden by the
// compiler
//
// Error! same reason as the previous Error
// println!("b contains: {}", b);
}
|
use crate::extracter::atcoder;
use std::io::Write;
use std::process::{Command, Stdio};
#[derive(Debug, PartialEq)]
pub struct SampleIO {
pub input: String,
pub output: String,
}
#[derive(Debug, PartialEq)]
pub struct Task {
pub title: String,
pub problem_statement: Option<String>,
pub sample_ios: Option<Vec<SampleIO>>,
pub io_style: Option<String>,
lang: atcoder::Lang,
pub url: String,
}
impl Task {
pub fn new(title: String, url: String, lang: atcoder::Lang) -> Task {
Task {
title: title,
problem_statement: None,
sample_ios: None,
io_style: None,
lang: lang,
url: url,
}
}
pub fn complete(&mut self) {
if self.problem_statement == None || self.sample_ios == None || self.io_style == None {
//TODO read data ans set
atcoder::set_task_info(self);
}
}
pub fn show(&self) -> bool {
let p_state = if let Some(statement) = &self.problem_statement {
statement
} else {
return false;
};
println!("title:\n{}", self.title);
println!("-----");
println!("statement:\n{}", p_state);
println!("-----");
if let Some(style) = &self.io_style {
print!("{}", style);
} else {
return false;
}
println!("-----");
if let Some(sample_vec) = &self.sample_ios {
println!("sample I/Os:");
for sample in sample_vec {
print!("{}{}", sample.input, sample.output);
println!("-----");
}
} else {
return false;
}
true
}
// this function returns a failed sample index;
pub fn run_test(&self, sample_num: i32, cmd: &String) -> Result<Vec<usize>, String> {
let mut failed_list = vec![];
if let Some(samples) = &self.sample_ios {
// run with all samples
if sample_num == -1 {
for (i, sample) in samples.iter().enumerate() {
let mut process = Command::new(cmd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.ok()
.expect("failed to start the program");
process
.stdin
.as_mut()
.unwrap()
.write(sample.input.as_bytes())
.unwrap();
println!("--- sample{:<02} ---\n", i);
let output = process.wait_with_output().unwrap();
let result_str = String::from_utf8(output.stdout).unwrap();
if result_str == sample.output {
println!("passed!");
} else {
println!("failed");
print!("correct answer is\n{}", sample.output);
print!("your answer is \n{}", result_str);
failed_list.push(i);
}
}
} else {
let index = sample_num as usize;
let sample = &samples[index];
let mut process = Command::new(cmd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.ok()
.expect("failed to start the program");
process
.stdin
.as_mut()
.unwrap()
.write(sample.input.as_bytes())
.unwrap();
let output = process.wait_with_output().unwrap();
let result_str = String::from_utf8(output.stdout).unwrap();
if result_str == sample.output {
println!("passed!\n");
} else {
println!("failed\n");
println!("correct answer is\n{}", sample.output);
println!("your answer is \n{}", result_str);
failed_list.push(index);
}
}
Ok(failed_list)
} else {
Err("cannot find any samples".to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_task() {
let domain = "atcoder.jp".to_string();
let path = "/contests/abc125/tasks".to_string();
let result = atcoder::get_tasks(&domain, &path);
let lang_ja = atcoder::Lang::Ja;
let mut task_result = vec![];
if let Some(tasks) = result {
for task in tasks {
task_result.push(Task::new(task.title, task.link, lang_ja));
}
} else {
assert!(false);
}
let answer = vec![
Task::new(
"A: Biscuit Generator".to_string(),
"https://atcoder.jp/contests/abc125/tasks/abc125_a".to_string(),
atcoder::Lang::Ja,
),
Task::new(
"B: Resale".to_string(),
"https://atcoder.jp/contests/abc125/tasks/abc125_b".to_string(),
atcoder::Lang::Ja,
),
Task::new(
"C: GCD on Blackboard".to_string(),
"https://atcoder.jp/contests/abc125/tasks/abc125_c".to_string(),
atcoder::Lang::Ja,
),
Task::new(
"D: Flipping Signs".to_string(),
"https://atcoder.jp/contests/abc125/tasks/abc125_d".to_string(),
atcoder::Lang::Ja,
),
];
assert_eq!(answer.len(), task_result.len());
for i in 0..answer.len() {
assert_eq!(answer[i], task_result[i]);
}
}
}
|
mod pong_server;
pub mod server;
|
use super::{
exp::Exp,
stm::Stm,
util::{WasmType, WasmTypeList},
};
pub type ModuleList = Vec<Module>;
pub type Module = Box<Module_>;
#[derive(Debug)]
pub enum Module_ {
Func(
i32,
WasmTypeList,
WasmTypeList,
WasmType,
Stm,
Option<String>,
),
JsImport(String, String, Module),
JsExport(String, i32),
Global(WasmType, Exp),
Data(String, Exp),
Elem(Exp, ModuleList),
Table(i32),
Type(WasmTypeList, WasmType),
Memory(i32),
None,
}
impl Module_ {
pub fn none_mod() -> Module {
Box::new(Module_::None)
}
pub fn func_mod(
index: i32,
params: WasmTypeList,
local: WasmTypeList,
result: WasmType,
body: Stm,
export_name: Option<String>,
) -> Module {
Box::new(Module_::Func(
index,
params,
local,
result,
body,
export_name,
))
}
pub fn jsimport_mod(name: String, module_name: String, module: Module) -> Module {
Box::new(Module_::JsImport(name, module_name, module))
}
pub fn jsexport_mod(name: String, index: i32) -> Module {
Box::new(Module_::JsExport(name, index))
}
pub fn global_mod(ty: WasmType, exp: Exp) -> Module {
Box::new(Module_::Global(ty, exp))
}
pub fn data_mod(data: String, exp: Exp) -> Module {
Box::new(Module_::Data(data, exp))
}
pub fn elem_mod(offset: Exp, funcs: ModuleList) -> Module {
Box::new(Module_::Elem(offset, funcs))
}
pub fn table_mod(size: i32) -> Module {
Box::new(Module_::Table(size))
}
pub fn type_mod(params: WasmTypeList, result: WasmType) -> Module {
Box::new(Module_::Type(params, result))
}
pub fn mem_mod(page_size: i32) -> Module {
Box::new(Module_::Memory(page_size))
}
}
|
use crate::{AnyBin, Segment};
/// A segment; segments can be joined to create binaries. See `BinBuilder`,
/// `SegmentIterator` and `SegmentsSlice`.
///
/// ```rust
/// use abin::{NewBin, BinSegment, Bin, AnyBin, BinBuilder};
///
/// let mut builder = NewBin::builder();
/// builder.push(BinSegment::Static("Hello, ".as_bytes()));
/// builder.push(BinSegment::Static("World!".as_bytes()));
/// let bin : Bin = builder.build();
///
/// assert_eq!("Hello, World!".as_bytes(), bin.as_slice());
/// ```
#[derive(Debug, Clone)]
pub enum BinSegment<'a, TAnyBin: AnyBin> {
Slice(&'a [u8]),
Static(&'static [u8]),
Bin(TAnyBin),
GivenVec(Vec<u8>),
Bytes128(Bytes128),
Empty,
}
impl<'a, TAnyBin> Segment for BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
#[inline]
fn number_of_bytes(&self) -> usize {
self.as_slice().len()
}
#[inline]
fn empty() -> Self {
Self::Empty
}
}
impl<'a, TAnyBin> BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
pub fn as_slice(&self) -> &[u8] {
match self {
BinSegment::Slice(slice) => *slice,
BinSegment::Static(slice) => *slice,
BinSegment::Bin(bin) => bin.as_slice(),
BinSegment::GivenVec(vec) => vec.as_slice(),
BinSegment::Bytes128(bytes) => bytes.as_slice(),
BinSegment::Empty => &[],
}
}
pub fn from_slice(slice: &'a [u8]) -> Self {
Self::Slice(slice)
}
}
impl<'a, TAnyBin> From<&'static [u8]> for BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
fn from(slice: &'static [u8]) -> Self {
Self::Static(slice)
}
}
impl<'a, TAnyBin> From<TAnyBin> for BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
fn from(bin: TAnyBin) -> Self {
Self::Bin(bin)
}
}
impl<'a, TAnyBin> From<Vec<u8>> for BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
fn from(vec: Vec<u8>) -> Self {
Self::GivenVec(vec)
}
}
impl<'a, TAnyBin> From<Bytes128> for BinSegment<'a, TAnyBin>
where
TAnyBin: AnyBin,
{
fn from(bytes: Bytes128) -> Self {
Self::Bytes128(bytes)
}
}
const BYTES_128_LEN: usize = 16;
/// Up to 16 bytes / 128 bit stored on the stack.
///
/// This can be used when constructing segments from primitive types (such as char, u64, f32
/// or f64).
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Bytes128 {
bytes: [u8; BYTES_128_LEN],
len: u8,
}
impl Bytes128 {
/// creates new bytes from given slice. Returns `None` if given slice contains more than
/// `max_number_of_bytes` bytes.
#[inline]
pub fn try_new(slice: &[u8]) -> Option<Self> {
let len = slice.len();
if len > BYTES_128_LEN {
None
} else {
let mut this = Self {
bytes: [0u8; BYTES_128_LEN],
len: len as u8,
};
let bytes = &mut this.bytes[0..len];
bytes.copy_from_slice(slice);
Some(this)
}
}
/// The maximum number of bytes that can be stored.
pub const fn max_number_of_bytes() -> usize {
BYTES_128_LEN
}
#[inline]
pub fn as_slice(&self) -> &[u8] {
&self.bytes[0..self.len as usize]
}
}
impl From<u8> for Bytes128 {
fn from(byte: u8) -> Self {
Self {
bytes: [byte, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
len: 1,
}
}
}
impl From<char> for Bytes128 {
fn from(chr: char) -> Self {
let mut buf = [0u8; 4];
let string = chr.encode_utf8(&mut buf);
Self::try_new(string.as_bytes()).expect(
"Implementation error: Converting from \
char cannot fail (since char takes 4 bytes whereas Bytes128 can take up to 16 bytes).",
)
}
}
|
use std::cmp::Reverse;
use std::collections::{BinaryHeap, LinkedList};
use rand::rngs::StdRng;
use crate::history::types::{HistoryEvent, HistoryEventBody, OrderOrigin};
use crate::message::{ExchangeReply, SubscriptionSchedule, SubscriptionUpdate, TraderRequest};
use crate::trader::Trader;
use crate::types::{DateTime, Duration, OrderID, Price, Size};
pub(crate) struct OrderBookLevel {
pub(crate) price: Price,
pub(crate) queue: LinkedList<OrderBookEntry>,
}
impl OrderBookLevel {
pub(crate) fn get_ob_level_size(&self) -> Size {
self.queue.iter().map(|order| order.size).sum()
}
}
pub(crate) struct OrderBookEntry {
pub(crate) order_id: OrderID,
pub(crate) size: Size,
pub(crate) from: OrderOrigin,
}
#[derive(Default)]
pub(crate) struct EventQueue(pub(crate) BinaryHeap<Reverse<Event>>);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) struct Event {
pub(crate) datetime: DateTime,
pub(crate) body: EventBody,
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) enum EventBody {
ExchangeOpenTryout,
HistoryEvent(HistoryEventBody),
TraderRequest(TraderRequest),
ExchangeReply(ExchangeReply, DateTime),
SubscriptionUpdate(SubscriptionUpdate, DateTime),
SubscriptionSchedule(SubscriptionSchedule),
TraderWakeUp,
ExchangeClosed,
}
impl Extend<Event> for EventQueue {
fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item=Event>
{
self.0.extend(iter.into_iter().map(Reverse))
}
}
impl EventQueue {
pub(crate) fn peek(&self) -> Option<&Event> {
match self.0.peek() {
Some(Reverse(event)) => { Some(event) }
_ => { None }
}
}
pub(crate) fn pop(&mut self) -> Option<Event> {
match self.0.pop() {
Some(Reverse(event)) => { Some(event) }
_ => { None }
}
}
pub(crate) fn push(&mut self, item: Event) {
self.0.push(Reverse(item))
}
pub(crate) fn schedule_reply_for_trader<T: Trader>(&mut self,
reply: ExchangeReply,
exchange_dt: DateTime,
rng: &mut StdRng) {
self.push(
Event {
datetime: exchange_dt + Duration::nanoseconds(T::exchange_to_trader_latency(rng, exchange_dt) as i64),
body: EventBody::ExchangeReply(reply, exchange_dt),
}
)
}
pub(crate) fn schedule_history_event(&mut self, event: HistoryEvent) {
self.push(
Event {
datetime: event.datetime,
body: EventBody::HistoryEvent(event.event),
}
)
}
} |
use std::time::Duration;
use eyre::Report;
use tokio::time::sleep;
use tokio_stream::StreamExt;
use twilight_gateway::Event;
use twilight_http::error::ErrorType;
use twilight_model::{
channel::{Message, Reaction, ReactionType},
id::{marker::UserMarker, Id},
};
use crate::{
commands::osu::{ProfileData, ProfileSize},
embeds::{EmbedData, ProfileEmbed},
pagination::ReactionWrapper,
util::{send_reaction, Emote},
BotResult, Context,
};
use super::{PageChange, PaginationResult, ReactionVec};
pub struct ProfilePagination {
msg: Message,
data: ProfileData,
current_size: ProfileSize,
}
impl ProfilePagination {
pub fn new(msg: Message, data: ProfileData, kind: ProfileSize) -> Self {
Self {
msg,
data,
current_size: kind,
}
}
fn reactions() -> ReactionVec {
smallvec![Emote::Expand, Emote::Minimize]
}
pub async fn start(
mut self,
ctx: &Context,
owner: Id<UserMarker>,
duration: u64,
) -> PaginationResult {
let msg_id = self.msg.id;
ctx.store_msg(msg_id);
let reactions = Self::reactions();
let reaction_stream = {
for emote in &reactions {
send_reaction(ctx, &self.msg, *emote).await?;
}
ctx.standby
.wait_for_event_stream(move |event: &Event| match event {
Event::ReactionAdd(event) => {
event.message_id == msg_id && event.user_id == owner
}
Event::ReactionRemove(event) => {
event.message_id == msg_id && event.user_id == owner
}
_ => false,
})
.map(|event| match event {
Event::ReactionAdd(add) => ReactionWrapper::Add(add.0),
Event::ReactionRemove(remove) => ReactionWrapper::Remove(remove.0),
_ => unreachable!(),
})
.timeout(Duration::from_secs(duration))
};
tokio::pin!(reaction_stream);
while let Some(Ok(reaction)) = reaction_stream.next().await {
if let Err(why) = self.next_page(reaction.into_inner(), ctx).await {
warn!("{:?}", Report::new(why).wrap_err("error while paginating"));
}
}
let msg = self.msg;
if !ctx.remove_msg(msg.id) {
return Ok(());
}
let delete_fut = ctx.http.delete_all_reactions(msg.channel_id, msg.id).exec();
if let Err(why) = delete_fut.await {
if matches!(why.kind(), ErrorType::Response { status, ..} if status.raw() == 403) {
sleep(Duration::from_millis(100)).await;
for emote in &reactions {
let reaction_reaction = emote.request_reaction_type();
ctx.http
.delete_current_user_reaction(msg.channel_id, msg.id, &reaction_reaction)
.exec()
.await?;
}
} else {
return Err(why.into());
}
}
Ok(())
}
async fn next_page(&mut self, reaction: Reaction, ctx: &Context) -> BotResult<PageChange> {
if self.process_reaction(&reaction.emoji) == PageChange::None {
return Ok(PageChange::None);
}
let embed = ProfileEmbed::get_or_create(ctx, self.current_size, &mut self.data).await;
ctx.http
.update_message(self.msg.channel_id, self.msg.id)
.embeds(Some(&[embed.as_builder().build()]))?
.exec()
.await?;
Ok(PageChange::Change)
}
fn process_reaction(&mut self, reaction: &ReactionType) -> PageChange {
match reaction {
ReactionType::Custom {
name: Some(name), ..
} => match name.as_str() {
"expand" => match self.current_size.expand() {
Some(size) => {
self.current_size = size;
PageChange::Change
}
None => PageChange::None,
},
"minimize" => match self.current_size.minimize() {
Some(size) => {
self.current_size = size;
PageChange::Change
}
None => PageChange::None,
},
_ => PageChange::None,
},
_ => PageChange::None,
}
}
}
|
use crate::mqtt::payload::Payload;
use crate::*;
use log::{debug, info, warn};
use std::sync::{Arc, Mutex};
pub struct Storage {
backend: Arc<Mutex<Box<dyn Backend + Send>>>,
}
impl Storage {
pub fn new() -> Self {
Self {
backend: Arc::new(Mutex::new(Box::new(BackendMock::default()))),
}
}
pub fn find_messages<S>(&mut self, pattern: S) -> Vec<String>
where
S: Into<String>,
{
let mut backend = self.backend.lock().unwrap();
backend.find_messages(pattern.into()).unwrap()
}
pub fn persist_message<S>(&mut self, topic: S, payload: Payload) -> Result<(), Error>
where
S: Into<String>,
{
let mut backend = self.backend.lock().unwrap();
backend.persist_message(topic.into(), payload)
}
}
pub trait Backend {
fn find_messages(&mut self, pattern: String) -> Result<Vec<String>, Error>;
fn persist_message(&mut self, topic: String, payload: Payload) -> Result<(), Error>;
}
pub struct BackendMock {
history: Vec<(String, Payload)>,
}
impl Default for BackendMock {
fn default() -> Self {
Self { history: vec![] }
}
}
impl Backend for BackendMock {
fn find_messages(&mut self, pattern: String) -> Result<Vec<String>, Error> {
info!("find messages with pattern: {}", pattern);
Ok(self
.history
.clone()
.into_iter()
.map(|(topic, _)| topic)
.collect())
// Ok(vec!["hallo", "du", "da"].into_iter().map(String::from).collect())
}
fn persist_message(&mut self, topic: String, payload: Payload) -> Result<(), Error> {
info!(
"persist messsage - topic: {}, payload: {:?}",
topic, payload
);
self.history.push((topic, payload));
Ok(())
}
}
|
use crate::{
embeds::{EmbedData, RankingEmbed, RankingEntry, RankingKindData},
pagination::{Pagination, RankingPagination},
util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
numbers, CountryCode, CowUtils, MessageExt,
},
BotResult, CommandData, Context,
};
use chrono::{DateTime, Utc};
use eyre::Report;
use rosu_v2::prelude::{GameMode, OsuResult, Rankings};
use std::{collections::BTreeMap, fmt, mem, sync::Arc};
fn country_code_(arg: &str) -> Result<CountryCode, &'static str> {
if arg.len() == 2 && arg.is_ascii() {
Ok(arg.to_ascii_uppercase().into())
} else if let Some(code) = CountryCode::from_name(arg) {
Ok(code)
} else {
Err("The given argument must be a valid country or country code of two ASCII letters")
}
}
pub(super) async fn _performanceranking(
ctx: Arc<Context>,
data: CommandData<'_>,
mut mode: GameMode,
country_code: Option<CountryCode>,
) -> BotResult<()> {
if mode == GameMode::STD {
mode = match ctx.user_config(data.author()?.id).await {
Ok(config) => config.mode.unwrap_or(GameMode::STD),
Err(why) => {
let _ = data.error(&ctx, GENERAL_ISSUE).await;
return Err(why);
}
};
}
let result = match country_code {
Some(ref country) => {
ctx.osu()
.performance_rankings(mode)
.country(country.as_str())
.await
}
None => ctx.osu().performance_rankings(mode).await,
};
let kind = RankingKind::Performance;
_ranking(ctx, data, mode, country_code, kind, result).await
}
pub(super) async fn _scoreranking(
ctx: Arc<Context>,
data: CommandData<'_>,
mut mode: GameMode,
) -> BotResult<()> {
if mode == GameMode::STD {
mode = match ctx.user_config(data.author()?.id).await {
Ok(config) => config.mode.unwrap_or(GameMode::STD),
Err(why) => {
let _ = data.error(&ctx, GENERAL_ISSUE).await;
return Err(why);
}
};
}
let result = ctx.osu().score_rankings(mode).await;
_ranking(ctx, data, mode, None, RankingKind::Score, result).await
}
async fn _ranking(
ctx: Arc<Context>,
data: CommandData<'_>,
mode: GameMode,
country_code: Option<CountryCode>,
kind: RankingKind,
result: OsuResult<Rankings>,
) -> BotResult<()> {
let mut ranking = match result {
Ok(ranking) => ranking,
Err(why) => {
let _ = data.error(&ctx, OSU_API_ISSUE).await;
return Err(why.into());
}
};
let country = country_code.map(|code| {
let name = ranking
.ranking
.get_mut(0)
.and_then(|user| mem::take(&mut user.country))
.unwrap_or_else(|| code.to_string());
(name, code)
});
let total = ranking.total as usize;
let pages = numbers::div_euclid(20, total);
let users: BTreeMap<_, _> = ranking
.ranking
.into_iter()
.map(|user| {
let stats = user.statistics.as_ref().unwrap();
let value = match kind {
RankingKind::Performance => UserValue::PpU32(stats.pp.round() as u32),
RankingKind::Score => UserValue::Amount(stats.ranked_score),
};
RankingEntry {
value,
name: user.username,
country: user.country_code.into(),
}
})
.enumerate()
.collect();
let ranking_kind_data = if let Some((name, code)) = country {
RankingKindData::PpCountry {
mode,
country_code: code,
country: name,
}
} else if kind == RankingKind::Performance {
RankingKindData::PpGlobal { mode }
} else {
RankingKindData::RankedScore { mode }
};
let embed_data = RankingEmbed::new(&users, &ranking_kind_data, None, (1, pages));
// Creating the embed
let builder = embed_data.into_builder().build().into();
let response = data.create_message(&ctx, builder).await?.model().await?;
// Pagination
let pagination = RankingPagination::new(
response,
Arc::clone(&ctx),
total,
users,
None,
ranking_kind_data,
);
let owner = data.author()?.id;
tokio::spawn(async move {
if let Err(err) = pagination.start(&ctx, owner, 60).await {
warn!("{:?}", Report::new(err));
}
});
Ok(())
}
#[command]
#[short_desc("Display the osu! pp ranking")]
#[long_desc(
"Display the osu! pp ranking.\n\
For the global ranking, don't give any arguments.\n\
For a country specific ranking, provide its name or country code as first argument."
)]
#[usage("[country]")]
#[example("", "de", "russia")]
#[aliases("ppr", "pplb", "ppleaderboard")]
pub async fn ppranking(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
let arg = args.next().map(CowUtils::cow_to_ascii_lowercase);
let country = match arg.as_deref().map(country_code_).transpose() {
Ok(country) => country,
Err(content) => return msg.error(&ctx, content).await,
};
let data = CommandData::Message { msg, args, num };
_performanceranking(ctx, data, GameMode::STD, country).await
}
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the osu!mania pp ranking")]
#[long_desc(
"Display the osu!mania pp ranking.\n\
For the global ranking, don't give any arguments.\n\
For a country specific ranking, provide its name or country code as first argument."
)]
#[usage("[country]")]
#[example("", "de", "russia")]
#[aliases("pprm", "pplbm", "ppleaderboardmania")]
pub async fn pprankingmania(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
let country = match args.next().map(country_code_).transpose() {
Ok(country) => country,
Err(content) => return msg.error(&ctx, content).await,
};
let data = CommandData::Message { msg, args, num };
_performanceranking(ctx, data, GameMode::MNA, country).await
}
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the osu!taiko pp ranking")]
#[long_desc(
"Display the osu!taiko pp ranking.\n\
For the global ranking, don't give any arguments.\n\
For a country specific ranking, provide its name or country code as first argument."
)]
#[usage("[country]")]
#[example("", "de", "russia")]
#[aliases("pprt", "pplbt", "ppleaderboardtaiko")]
pub async fn pprankingtaiko(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
let country = match args.next().map(country_code_).transpose() {
Ok(country) => country,
Err(content) => return msg.error(&ctx, content).await,
};
let data = CommandData::Message { msg, args, num };
_performanceranking(ctx, data, GameMode::TKO, country).await
}
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the osu!ctb pp ranking")]
#[long_desc(
"Display the osu!ctb pp ranking.\n\
For the global ranking, don't give any arguments.\n\
For a country specific ranking, provide its name or country code as first argument."
)]
#[usage("[country]")]
#[example("", "de", "russia")]
#[aliases("pprc", "pplbc", "ppleaderboardctb")]
pub async fn pprankingctb(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
let country = match args.next().map(country_code_).transpose() {
Ok(country) => country,
Err(content) => return msg.error(&ctx, content).await,
};
let data = CommandData::Message { msg, args, num };
_performanceranking(ctx, data, GameMode::CTB, country).await
}
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the global osu! ranked score ranking")]
#[aliases("rsr", "rslb")]
pub async fn rankedscoreranking(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
data @ CommandData::Message { .. } => _scoreranking(ctx, data, GameMode::STD).await,
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the global osu!mania ranked score ranking")]
#[aliases("rsrm", "rslbm")]
pub async fn rankedscorerankingmania(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
data @ CommandData::Message { .. } => _scoreranking(ctx, data, GameMode::MNA).await,
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the global osu!taiko ranked score ranking")]
#[aliases("rsrt", "rslbt")]
pub async fn rankedscorerankingtaiko(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
data @ CommandData::Message { .. } => _scoreranking(ctx, data, GameMode::TKO).await,
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[command]
#[short_desc("Display the global osu!ctb ranked score ranking")]
#[aliases("rsrc", "rslbc")]
pub async fn rankedscorerankingctb(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
data @ CommandData::Message { .. } => _scoreranking(ctx, data, GameMode::CTB).await,
CommandData::Interaction { command } => super::slash_ranking(ctx, *command).await,
}
}
#[derive(Eq, PartialEq)]
pub enum RankingKind {
Performance,
Score,
}
#[derive(Copy, Clone)]
pub enum UserValue {
Accuracy(f32),
Amount(u64),
AmountWithNegative(i64),
Date(DateTime<Utc>),
Float(f32),
Playtime(u32),
PpF32(f32),
PpU32(u32),
Rank(u32),
}
impl fmt::Display for UserValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Accuracy(acc) => write!(f, "{:.2}%", numbers::round(acc)),
Self::Amount(amount) => write!(f, "{}", Self::AmountWithNegative(amount as i64)),
Self::AmountWithNegative(amount) => {
if amount.abs() < 1_000_000_000 {
write!(f, "{}", numbers::with_comma_int(amount))
} else {
let score = (amount / 10_000_000) as f32 / 100.0;
write!(f, "{score:.2} bn")
}
}
Self::Date(date) => write!(f, "{}", date.format("%F")),
Self::Float(v) => write!(f, "{:.2}", numbers::round(v)),
Self::Playtime(seconds) => {
write!(f, "{} hrs", numbers::with_comma_int(seconds / 60 / 60))
}
Self::PpF32(pp) => write!(f, "{}pp", numbers::with_comma_float(numbers::round(pp))),
Self::PpU32(pp) => write!(f, "{}pp", numbers::with_comma_int(pp)),
Self::Rank(rank) => write!(f, "#{}", numbers::with_comma_int(rank)),
}
}
}
|
use ::std::env::current_dir;
use ::anyhow::{anyhow, Result};
use ::pueue::message::*;
use crate::cli::{SubCommand, Opt};
// Convert and pre-process the sub-command into a valid message
// that can be understood by the daemon
pub fn get_message_from_opt(opt: &Opt) -> Result<Message> {
match &opt.cmd {
SubCommand::Add {
command,
start_immediately,
create_stashed,
} => {
let cwd_pathbuf = current_dir()?;
let cwd = cwd_pathbuf.to_str().ok_or(anyhow!(
"Cannot parse current working directory (Invalid utf8?)"
))?;
Ok(Message::Add(AddMessage {
command: command.join(" "),
path: cwd.to_string(),
start_immediately: *start_immediately,
create_stashed: *create_stashed,
}))
}
SubCommand::Remove { task_ids } => {
let message = RemoveMessage {
task_ids: task_ids.clone(),
};
Ok(Message::Remove(message))
}
SubCommand::Stash { task_ids } => {
let message = StashMessage {
task_ids: task_ids.clone(),
};
Ok(Message::Stash(message))
}
SubCommand::Switch {
task_id_1,
task_id_2,
} => {
let message = SwitchMessage {
task_id_1: *task_id_1,
task_id_2: *task_id_2,
};
Ok(Message::Switch(message))
}
SubCommand::Enqueue { task_ids } => {
let message = EnqueueMessage {
task_ids: task_ids.clone(),
};
Ok(Message::Enqueue(message))
}
SubCommand::Start { task_ids } => {
let message = StartMessage {
task_ids: task_ids.clone(),
};
Ok(Message::Start(message))
}
SubCommand::Restart {
task_ids,
start_immediately,
} => {
let message = RestartMessage {
task_ids: task_ids.clone(),
start_immediately: *start_immediately,
};
Ok(Message::Restart(message))
}
SubCommand::Pause { wait, task_ids } => {
let message = PauseMessage {
wait: *wait,
task_ids: task_ids.clone(),
};
Ok(Message::Pause(message))
}
SubCommand::Kill { all, task_ids } => {
let message = KillMessage {
all: *all,
task_ids: task_ids.clone(),
};
Ok(Message::Kill(message))
}
SubCommand::Send { task_id, input } => {
let message = SendMessage {
task_id: *task_id,
input: input.clone(),
};
Ok(Message::Send(message))
}
SubCommand::Edit { task_id } => {
let message = EditRequestMessage { task_id: *task_id };
Ok(Message::EditRequest(message))
}
SubCommand::Status { json: _ } => Ok(Message::SimpleStatus),
SubCommand::Log {
task_ids: _,
json: _,
} => Ok(Message::Status),
SubCommand::Show {
task_id,
follow,
err,
} => {
let message = StreamRequestMessage {
task_id: *task_id,
follow: *follow,
err: *err,
};
Ok(Message::StreamRequest(message))
}
SubCommand::Clean => Ok(Message::Clean),
SubCommand::Reset => Ok(Message::Reset),
SubCommand::Shutdown => Ok(Message::DaemonShutdown),
SubCommand::Parallel { parallel_tasks } => Ok(Message::Parallel(*parallel_tasks)),
}
}
|
extern crate bit_set;
extern crate rand;
use bit_set::BitSet;
use rand::prelude::*;
// how does this differ from
// use crate::model::*; ?
use super::model::*;
use super::parameters::*;
///
/// Generate a new chromosome by randomly generating an allele for each site.
///
fn randomly_generate_chromosome(params: &SimParameters) -> Chromosome {
let mut rng = rand::thread_rng();
let mut alleles = BitSet::new();
for i in 0..params.chromosome_length {
if rng.gen_bool(0.5) {
alleles.insert(i);
}
}
Chromosome {
alleles: alleles,
inverted: false
}
}
///
/// Generate a population of individuals by randomly generating two chromosomes
/// for each individual.
///
pub fn randomly_generate_population(params: &SimParameters) -> Population {
let mut individuals: Vec<Individual> = Vec::new();
for _ in 0..params.n_individuals {
let chrom = randomly_generate_chromosome(params);
let individual = [chrom.clone(), chrom.clone()];
individuals.push(individual);
}
individuals
}
///
/// Clone a population from a single randomly-generated individual.
///
pub fn clone_population(params: &SimParameters) -> Population {
let mut individuals: Vec<Individual> = Vec::with_capacity(params.n_individuals);
let chrom = Chromosome {
alleles: BitSet::new(),
inverted: false
};
let individual = [chrom.clone(), chrom.clone()];
for _ in 0..params.n_individuals {
individuals.push(individual.clone());
}
individuals
}
|
use crate::arch::x64::CPUPrivLevel;
pub const KERNEL_UID: usize = 0;
pub const SUPERUSER_UID: usize = 1;
pub const IOPRIV_UID: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PrivLevel
{
Kernel,
SuperUser,
IOPriv,
User(usize),
}
impl PrivLevel
{
pub fn new(uid: usize) -> Self
{
match uid {
KERNEL_UID => Self::Kernel,
SUPERUSER_UID => Self::SuperUser,
IOPRIV_UID => Self::IOPriv,
_ => Self::User(uid),
}
}
pub fn uid(&self) -> usize
{
match self {
Self::Kernel => KERNEL_UID,
Self::SuperUser => SUPERUSER_UID,
Self::IOPriv => IOPRIV_UID,
Self::User(uid) => *uid,
}
}
pub fn as_cpu_priv(&self) -> CPUPrivLevel
{
match self {
Self::Kernel => CPUPrivLevel::Ring0,
_ => CPUPrivLevel::Ring3,
}
}
}
|
use ffi::lto::*;
use std::ops::Drop;
use std::ffi::{CStr, CString};
use libc::{c_char, c_uint, c_void};
use object::Symbol;
use context::Context;
use std::mem;
pub struct LTOCodeGenerator(*mut LLVMOpaqueLTOCodeGenerator);
pub struct LTOModule(*mut LLVMOpaqueLTOModule);
pub enum LTODebugModel {
DWARF,
None,
}
pub enum LTOPicModel {
Static,
Dynamic,
DynamicNoPic,
Default,
}
pub enum LTOSymbolAttributes {
MaskAlignment,
MaskPermissions,
CodePermissions,
DataPermissions,
RoDataPermissions,
MaskDefinition,
RegularDefinition,
TentativeDefinition,
WeakDefinition,
UndefinedDefinition,
WeakUndefindedDefinition,
MaskScope,
InternalScope,
HiddenScope,
ProtectedScope,
DefualtScope,
ScopeCanBeHidden,
Comdat,
Alias,
}
pub enum LTODiagnosticSeverity {
}
impl LTOCodeGenerator {
pub fn new() -> Self {
LTOCodeGenerator(unsafe { lto_codegen_create() })
}
fn get(&self) -> *mut LLVMOpaqueLTOCodeGenerator {
self.0
}
pub fn add_module(&self, module: LTOModule) -> Result<(), String> {
if unsafe { lto_codegen_add_module(self.get(), module.0) } == (false as u8) {
Ok(())
} else {
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
}
}
/// Adds a symbol to the list of global symbols that must exist in the final
/// generated code. If a function is not listed there, it might be inlined into
/// every usage and optimized away. For every single module, the functions
/// referenced from code outside of the ThinLTO modules need to be added here.
pub fn preserve_symbol(&self, symbol: Symbol) {
unsafe { lto_codegen_add_must_preserve_symbol(self.get(), symbol.get()) }
}
pub fn compile(&self) {
unimplemented!()
}
/// Sets debug option
pub fn debug_options(&self, opts: &str) {
unsafe { lto_codegen_debug_options(self.get(), opts.as_ptr() as *const c_char) }
}
/// Runs optimization for the merged module
pub fn optimize(&self) -> Result<(), String> {
if unsafe { lto_codegen_optimize(self.get()) } == true as u8 {
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
} else {
Ok(())
}
}
/// Sets extra arguments that libLTO should pass to the assembler
pub fn assembler_args(&self, args: Vec<&str>) {
unsafe {
lto_codegen_set_assembler_args(
self.get(),
args.join("").as_ptr() as *mut *const c_char,
args.len() as i32,
)
}
}
/// Sets the location of the assembler tool to run. If not set, libLTO
/// will use gcc to invoke the assembler
pub fn assembler_path(&self, path: &str) {
unsafe { lto_codegen_set_assembler_path(self.get(), path.as_ptr() as *const c_char) }
}
/// Sets the cpu to generate code for
pub fn set_cpu(&self, cpu: &str) {
unsafe { lto_codegen_set_cpu(self.get(), cpu.as_ptr() as *const c_char) }
}
/// Sets if debug info should be generated.
pub fn set_debug_model(&self, model: LTODebugModel) -> Result<(), String> {
if unsafe { lto_codegen_set_debug_model(self.get(), model.into()) } == true as u8 {
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
} else {
Ok(())
}
}
///Sets the object module for code gneeration. This will transfer ownership of the module to the code generator.
pub fn set_module(&self, module: LTOModule) {
unsafe { lto_codegen_set_module(self.get(), module.0) }
}
/// Sets which PIC code model to generated
pub fn set_pic_model(&self, model: LTOPicModel) -> Result<(), String> {
if unsafe { lto_codegen_set_pic_model(self.get(), model.into()) } == true as u8 {
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
} else {
Ok(())
}
}
/// Set whether to embed uselists in bitcode.
pub fn should_use_embed_lists(&self, flag: bool) {
unsafe { lto_codegen_set_should_embed_uselists(self.get(), flag as u8) }
}
pub fn should_internalize(&self, flag: bool) {
unsafe { lto_codegen_set_should_internalize(self.get(), flag as u8) }
}
/// Writes a new object file at the specified path that contains the
/// merged contents of all modules added so far
pub fn write_modules(&self, path: &str) -> Result<(), String> {
if unsafe { lto_codegen_write_merged_modules(self.get(), path.as_ptr() as *const c_char) }
== true as u8
{
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
} else {
Ok(())
}
}
/// Initializes LLVM disassemblers
pub fn init_disassembler(&self) {
unsafe { lto_initialize_disassembler() }
}
}
impl Drop for LTOCodeGenerator {
fn drop(&mut self) {
unsafe { lto_codegen_dispose(self.get()) }
}
}
impl From<LTODebugModel> for lto_debug_model {
fn from(model: LTODebugModel) -> lto_debug_model {
match model {
LTODebugModel::None => lto_debug_model::LTO_DEBUG_MODEL_NONE,
LTODebugModel::DWARF => lto_debug_model::LTO_DEBUG_MODEL_DWARF,
}
}
}
impl From<LTOPicModel> for lto_codegen_model {
fn from(model: LTOPicModel) -> lto_codegen_model {
match model {
LTOPicModel::Static => lto_codegen_model::LTO_CODEGEN_PIC_MODEL_STATIC,
LTOPicModel::Dynamic => lto_codegen_model::LTO_CODEGEN_PIC_MODEL_DYNAMIC,
LTOPicModel::DynamicNoPic => lto_codegen_model::LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC,
LTOPicModel::Default => lto_codegen_model::LTO_CODEGEN_PIC_MODEL_DEFAULT,
}
}
}
impl From<lto_symbol_attributes> for LTOSymbolAttributes {
fn from(attribute: lto_symbol_attributes) -> LTOSymbolAttributes {
match attribute {
lto_symbol_attributes::LTO_SYMBOL_ALIGNMENT_MASK => LTOSymbolAttributes::MaskAlignment,
lto_symbol_attributes::LTO_SYMBOL_PERMISSIONS_MASK => {
LTOSymbolAttributes::MaskPermissions
}
lto_symbol_attributes::LTO_SYMBOL_PERMISSIONS_CODE => {
LTOSymbolAttributes::CodePermissions
}
lto_symbol_attributes::LTO_SYMBOL_PERMISSIONS_DATA => {
LTOSymbolAttributes::DataPermissions
}
lto_symbol_attributes::LTO_SYMBOL_PERMISSIONS_RODATA => {
LTOSymbolAttributes::RoDataPermissions
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_MASK => {
LTOSymbolAttributes::MaskDefinition
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_REGULAR => {
LTOSymbolAttributes::RegularDefinition
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_TENTATIVE => {
LTOSymbolAttributes::TentativeDefinition
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_WEAK => {
LTOSymbolAttributes::WeakDefinition
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_UNDEFINED => {
LTOSymbolAttributes::UndefinedDefinition
}
lto_symbol_attributes::LTO_SYMBOL_DEFINITION_WEAKUNDEF => {
LTOSymbolAttributes::WeakUndefindedDefinition
}
lto_symbol_attributes::LTO_SYMBOL_SCOPE_MASK => LTOSymbolAttributes::MaskScope,
lto_symbol_attributes::LTO_SYMBOL_SCOPE_INTERNAL => LTOSymbolAttributes::InternalScope,
lto_symbol_attributes::LTO_SYMBOL_SCOPE_HIDDEN => LTOSymbolAttributes::HiddenScope,
lto_symbol_attributes::LTO_SYMBOL_SCOPE_PROTECTED => {
LTOSymbolAttributes::ProtectedScope
}
lto_symbol_attributes::LTO_SYMBOL_SCOPE_DEFAULT => LTOSymbolAttributes::DefualtScope,
lto_symbol_attributes::LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN => {
LTOSymbolAttributes::ScopeCanBeHidden
}
lto_symbol_attributes::LTO_SYMBOL_COMDAT => LTOSymbolAttributes::Comdat,
lto_symbol_attributes::LTO_SYMBOL_ALIAS => LTOSymbolAttributes::Alias,
}
}
}
impl LTOModule {
pub fn new(path: &str) -> LTOModule {
LTOModule(unsafe { lto_module_create(path.as_ptr() as *const c_char) })
}
fn get(&self) -> *mut LLVMOpaqueLTOModule {
self.0
}
/// Loads an object file into the same context as codegenerator. The module is safe to
// add using `lto_codegen_add_module()`
pub fn with_context(mut ctx: &Context, path: &str) -> Result<(), String> {
let length = mem::size_of::<Context>();
let ctx_ptr: *mut c_void = &mut ctx as *mut _ as *mut c_void;
if unsafe {
lto_module_create_in_local_context(ctx_ptr, length, path.as_ptr() as *const c_char)
}.is_null()
{
let error = unsafe { CStr::from_ptr(lto_get_error_message()) };
Err(CString::from(error).into_string().unwrap())
} else {
Ok(())
}
}
/// Returns the module's linker options
pub fn linker_opts(&self) -> &str {
let opts = unsafe { CStr::from_ptr(lto_module_get_linkeropts(self.get())) };
opts.to_str().unwrap()
}
/// Returns the number of symbols in the object module
pub fn num_symbols(&self) -> c_uint {
unsafe { lto_module_get_num_symbols(self.get()) }
}
/// Returns the attributes of the ith symbol in the object module.
pub fn symbol_attribute(&self, index: c_uint) -> LTOSymbolAttributes {
unsafe { lto_module_get_symbol_attribute(self.get(), index) }.into()
}
/// Returns the name of the ith symbol in the object module
pub fn symbol_name(&self, index: c_uint) -> &str {
unsafe {
CStr::from_ptr(lto_module_get_symbol_name(self.get(), index))
.to_str()
.unwrap()
}
}
pub fn target_triple(&self) -> &str {
unsafe {
CStr::from_ptr(lto_module_get_target_triple(self.get()))
.to_str()
.unwrap()
}
}
pub fn is_object_file(&self, path: &str) -> bool {
unsafe { lto_module_is_object_file(path.as_ptr() as *const c_char) != 0 }
}
pub fn is_for_target(&self, path: &str, target: &str) -> bool {
unsafe {
lto_module_is_object_file_for_target(
path.as_ptr() as *const c_char,
target.as_ptr() as *const c_char,
) != 0
}
}
pub fn is_thinlto(&self) -> bool {
unsafe { lto_module_is_thinlto(self.get()) != 0 }
}
}
impl Drop for LTOModule {
fn drop(&mut self) {
unsafe { lto_module_dispose(self.get()) }
}
}
|
#[doc = "Register `COMP_ID_1` reader"]
pub type R = crate::R<COMP_ID_1_SPEC>;
#[doc = "Field `PREAMBLE` reader - Preamble bits 8 to 11"]
pub type PREAMBLE_R = crate::FieldReader;
#[doc = "Field `CLASS` reader - Component class"]
pub type CLASS_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - Preamble bits 8 to 11"]
#[inline(always)]
pub fn preamble(&self) -> PREAMBLE_R {
PREAMBLE_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - Component class"]
#[inline(always)]
pub fn class(&self) -> CLASS_R {
CLASS_R::new(((self.bits >> 4) & 0x0f) as u8)
}
}
#[doc = "AXI interconnect - component ID1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_id_1::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct COMP_ID_1_SPEC;
impl crate::RegisterSpec for COMP_ID_1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`comp_id_1::R`](R) reader structure"]
impl crate::Readable for COMP_ID_1_SPEC {}
#[doc = "`reset()` method sets COMP_ID_1 to value 0x04"]
impl crate::Resettable for COMP_ID_1_SPEC {
const RESET_VALUE: Self::Ux = 0x04;
}
|
#[doc = "Reader of register ISPENDR4"]
pub type R = crate::R<u32, super::ISPENDR4>;
#[doc = "Writer for register ISPENDR4"]
pub type W = crate::W<u32, super::ISPENDR4>;
#[doc = "Register ISPENDR4 `reset()`'s with value 0"]
impl crate::ResetValue for super::ISPENDR4 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `ISPENDR4`"]
pub type ISPENDR4_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `ISPENDR4`"]
pub struct ISPENDR4_W<'a> {
w: &'a mut W,
}
impl<'a> ISPENDR4_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - interrupt set-pending"]
#[inline(always)]
pub fn ispendr4(&self) -> ISPENDR4_R {
ISPENDR4_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - interrupt set-pending"]
#[inline(always)]
pub fn ispendr4(&mut self) -> ISPENDR4_W {
ISPENDR4_W { w: self }
}
}
|
mod day1;
pub use crate::day1::day1;
mod day2;
pub use crate::day2::day2;
mod day3;
pub use crate::day3::day3;
mod day4;
pub use crate::day4::day4;
mod day5;
pub use crate::day5::day5;
mod day6;
pub use crate::day6::day6;
mod day7;
pub use crate::day7::day7;
mod day8;
pub use crate::day8::day8;
mod day9;
pub use crate::day9::day9;
mod day10;
pub use crate::day10::day10;
mod day11;
pub use crate::day11::day11;
mod day12;
pub use crate::day12::day12;
mod day13;
pub use crate::day13::day13;
mod day14;
pub use crate::day14::day14;
mod day15;
pub use crate::day15::day15;
mod day16;
pub use crate::day16::day16;
mod day17;
pub use crate::day17::day17;
mod day18;
pub use crate::day18::day18;
mod day20;
pub use crate::day20::day20;
mod day21;
pub use crate::day21::day21;
mod day24;
pub use crate::day24::day24;
mod day25;
pub use crate::day25::day25;
mod day18_assist;
pub use crate::day18_assist::calculate;
mod utils;
pub use crate::utils::*;
|
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
/// Unique identifier for this user or bot
pub id: i32,
/// True, if this user is a bot
pub is_bot: bool,
/// User‘s or bot’s first name
pub first_name: String,
/// User‘s or bot’s last name
pub last_name: Option<String>,
/// User‘s or bot’s username
pub username: Option<String>,
/// [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag) of the user's language
pub language_code: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WebhookInfo {
/// Webhook URL, may be empty if webhook is not set up
pub url: String,
/// True, if a custom certificate was provided for webhook certificate checks
pub has_custom_certificate: bool,
/// Number of updates awaiting delivery
pub pending_update_count: i32,
/// Unix time for the most recent error that happened when trying to deliver an update via webhook
pub last_error_date: Option<i32>,
/// Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
pub last_error_message: Option<String>,
/// Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
pub max_connections: Option<i32>,
/// A list of update types the bot is subscribed to. Defaults to all update types
pub allowed_updates: Option<Vec<String>>,
}
/// This object represents an incoming update.
/// At most one of the optional parameters can be present in any given update.
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Update {
/// The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.
pub update_id: i32,
/// New incoming message of any kind — text, photo, sticker, etc.
#[serde(flatten)]
pub message: UpdateMessage,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum UpdateMessage {
/// New incoming message of any kind — text, photo, sticker, etc.
Message(Message),
/// New version of a message that is known to the bot and was edited
EditedMessage(Message),
/// New incoming channel post of any kind — text, photo, sticker, etc.
ChannelPost(Message),
/// New version of a channel post that is known to the bot and was edited
EditedChannelPost(Message),
/// New incoming inline query
InlineQuery(InlineQuery),
/// The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.
ChosenInlineResult(ChosenInlineResult),
/// New incoming callback query
CallbackQuery(CallbackQuery),
/// New incoming shipping query. Only for invoices with flexible price
ShippingQuery(ShippingAddress),
/// New incoming pre-checkout query. Contains full information about checkout
PreCheckoutQuery(PreCheckoutQuery),
/// New poll state. Bots receive only updates about polls, which are sent or stopped by the bot
Poll(Poll),
#[serde(other)]
Unknown,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all(serialize = "lowercase", deserialize = "lowercase"))]
pub enum ChatType {
Private,
Group,
SuperGroup,
Channel,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Chat {
/// Unique identifier for this chat.
pub id: i64,
/// Type of chat
#[serde(rename = "type")]
pub chat_type: ChatType,
/// Title, for supergroups, channels and group chats
pub title: Option<String>,
/// Username, for private chats, supergroups and channels if available
pub username: Option<String>,
/// First name of the other party in a private chat
pub first_name: Option<String>,
/// Last name of the other party in a private chat
pub last_name: Option<String>,
/// True if a group has ‘All Members Are Admins’ enabled.
pub all_members_are_administrators: Option<bool>,
/// Chat photo. Returned only in getChat.
pub photo: Option<ChatPhoto>,
/// Description, for supergroups and channel chats. Returned only in getChat.
pub description: Option<String>,
/// Chat invite link, for supergroups and channel chats. Each administrator in a chat generates their own invite links, so the bot must first generate the link using exportChatInviteLink. Returned only in getChat.
pub invite_link: Option<String>,
/// Pinned message, for groups, supergroups and channels. Returned only in getChat.
pub pinned_message: Option<Box<Message>>,
/// For supergroups, name of group sticker set. Returned only in getChat.
pub sticker_set_name: Option<String>,
/// True, if the bot can change the group sticker set. Returned only in getChat.
pub can_set_sticker_set: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Message {
pub message_id: i32,
pub from: Option<User>,
pub date: i32,
pub chat: Box<Chat>,
pub forward_from: Option<User>,
pub forward_from_chat: Option<Box<Chat>>,
pub forward_from_message_id: Option<i32>,
pub forward_signature: Option<String>,
pub forward_sender_name: Option<String>,
pub forward_date: Option<i32>,
pub reply_to_message: Option<Box<Message>>,
pub edit_date: Option<i32>,
pub media_group_id: Option<String>,
pub author_signature: Option<String>,
pub text: Option<String>,
pub entities: Option<Vec<MessageEntity>>,
pub caption_entities: Option<Vec<MessageEntity>>,
pub audio: Option<Audio>,
pub document: Option<Document>,
pub animation: Option<Animation>,
pub game: Option<Game>,
pub photo: Option<Vec<PhotoSize>>,
pub sticker: Option<Sticker>,
pub video: Option<Video>,
pub voice: Option<Voice>,
pub video_note: Option<VideoNote>,
pub caption: Option<String>,
pub contact: Option<Contact>,
pub location: Option<Location>,
pub venue: Option<Venue>,
pub poll: Option<Poll>,
pub new_chat_members: Option<Vec<User>>,
pub left_chat_member: Option<User>,
pub new_chat_title: Option<String>,
pub new_chat_photo: Option<Vec<PhotoSize>>,
pub delete_chat_photo: Option<bool>,
pub group_chat_created: Option<bool>,
pub supergroup_chat_created: Option<bool>,
pub channel_chat_created: Option<bool>,
pub migrate_to_chat_id: Option<bool>,
pub migrate_from_chat_id: Option<i64>,
pub pinned_message: Option<Box<Message>>,
pub invoice: Option<Invoice>,
pub successful_payment: Option<SuccessfulPayment>,
pub connected_website: Option<String>,
pub passport_data: Option<PassportData>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MessageEntity {
#[serde(rename = "type")]
pub message_type: String,
pub offset: i32,
pub length: i32,
pub url: Option<String>,
pub user: Option<User>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InlineQuery {
pub id: String,
pub from: User,
pub location: Option<Location>,
pub query: String,
pub offset: String,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PhotoSize {
pub file_id: String,
pub width: i32,
pub height: i32,
pub file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Audio {
pub file_id: String,
pub duration: i32,
pub performer: Option<String>,
pub title: Option<String>,
pub mime_type: Option<String>,
pub file_size: Option<i32>,
pub thumb: Option<PhotoSize>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Document {
pub file_id: String,
pub thumb: Option<PhotoSize>,
pub file_name: Option<String>,
pub mime_type: Option<String>,
pub file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Video {
pub file_id: String,
pub width: i32,
pub height: i32,
pub duration: i32,
pub thumb: Option<PhotoSize>,
pub mime_type: Option<String>,
pub file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Animation {
pub file_id: String,
pub width: i32,
pub height: i32,
pub duration: i32,
pub thumb: Option<PhotoSize>,
pub file_name: Option<String>,
pub mime_type: Option<String>,
pub file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChosenInlineResult {
pub result_id: String,
pub from: User,
pub location: Option<Location>,
pub inline_message_id: Option<String>,
pub query: String,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ShippingQuery {
pub id: String,
pub from: User,
pub invoice_payload: String,
pub shipping_address: ShippingAddress,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PreCheckoutQuery {
pub id: String,
pub from: User,
pub currency: String,
pub total_amount: i32,
pub invoice_payload: String,
pub shipping_option_id: Option<String>,
pub order_info: Option<OrderInfo>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Voice {
file_id: String,
duration: i32,
mime_type: Option<String>,
file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VideoNote {
file_id: String,
length: i32,
duration: i32,
thumb: Option<PhotoSize>,
file_size: Option<i32>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Contact {
phone_number: String,
first_name: String,
last_name: Option<String>,
user_id: Option<i32>,
vcard: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Location {
longitude: f64,
latitude: f64,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Venue {
location: Location,
title: String,
address: String,
foursquare_id: Option<String>,
foursquare_type: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PollOption {
text: String,
voter_count: i32,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Poll {
id: String,
question: String,
options: Vec<PollOption>,
is_closed: bool,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserProfilePhotos {
total_count: i32,
photo: Vec<Vec<PhotoSize>>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct File {
file_id: String,
file_unique_id: String,
file_size: Option<i32>,
file_path: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ReplyKeyboardMarkup {
keyboard: Vec<Vec<KeyboardButton>>,
resize_keyboard: Option<bool>,
one_time_keyboard: Option<bool>,
selective: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct KeyboardButton {
text: String,
request_contact: Option<bool>,
request_location: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ReplyKeyboardRemove {
/// should be true
remove_keyboard: bool,
selective: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InlineKeyboardMarkup {
pub inline_keyboard: Vec<Vec<InlineKeyboardButton>>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InlineKeyboardButton {
pub text: String,
pub url: Option<String>,
pub callback_data: Option<String>,
pub switch_inline_query: Option<String>,
pub switch_inline_query_current_chat: Option<String>,
pub callback_game: Option<CallbackGame>,
pub pay: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CallbackQuery {
id: String,
from: User,
message: Option<Message>,
inline_message_id: Option<String>,
chat_instance: String,
data: Option<String>,
game_short_name: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ForceReply {
/// should be true
force_reply: bool,
selective: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChatPhoto {
small_file_id: String,
big_file_id: String,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ChatMemberStatus {
Creator,
Administrator,
Member,
Restricted,
Left,
Kicked,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChatMember {
user: User,
status: ChatMemberStatus,
until_date: Option<i32>,
can_be_edited: Option<bool>,
can_change_info: Option<bool>,
can_post_messages: Option<bool>,
can_edit_messages: Option<bool>,
can_delete_messages: Option<bool>,
can_invite_users: Option<bool>,
can_restrict_members: Option<bool>,
can_pin_messages: Option<bool>,
can_promote_members: Option<bool>,
is_member: Option<bool>,
can_send_messages: Option<bool>,
can_send_media_messages: Option<bool>,
can_send_other_message: Option<bool>,
can_add_web_page_previews: Option<bool>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResponseParameters {
migrate_to_chat_id: Option<i32>,
retry_after: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum InputMedia {
Animation(InputMediaAnimation),
Document(InputMediaDocument),
Audio(InputMediaAudio),
Photo(InputMediaPhoto),
Video(InputMediaVideo),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ParseMode {
Markdown,
Html,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InputMediaPhoto {
/// always be photo
#[serde(rename = "type")]
photo_type: String,
media: String,
caption: Option<String>,
parse_mode: Option<ParseMode>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InputMediaVideo {
#[serde(rename = "type")]
video_type: String,
media: String,
/// TODO inputFile
thumb: Option<String>,
caption: Option<String>,
parse_mode: Option<ParseMode>,
width: Option<i32>,
height: Option<i32>,
duration: Option<i32>,
supports_streaming: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InputMediaAudio {
#[serde(rename = "type")]
audio_type: String,
media: String,
thumb: Option<String>,
caption: Option<String>,
parse_mod: Option<ParseMode>,
duration: Option<i32>,
performer: Option<String>,
title: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InputMediaAnimation {
#[serde(rename = "type")]
animation_type: String,
media: String,
thumb: Option<String>,
caption: Option<String>,
parse_mode: Option<ParseMode>,
width: Option<i32>,
height: Option<i32>,
duration: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InputMediaDocument {
#[serde(rename = "type")]
document_type: String,
media: String,
thumb: Option<String>,
caption: Option<String>,
parse_mode: Option<ParseMode>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Sticker {
file_id: String,
width: i32,
height: i32,
thumb: Option<PhotoSize>,
emoji: Option<String>,
set_name: Option<String>,
mask_position: Option<String>,
fil_size: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Game {
title: String,
description: String,
photo: Vec<PhotoSize>,
text: Option<String>,
text_entities: Option<Vec<MessageEntity>>,
animation: Option<Animation>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CallbackGame;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Invoice {
title: String,
description: String,
start_parameter: String,
currency: String,
total_amount: i32,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SuccessfulPayment {
currency: String,
total_amount: i32,
invoice_payload: String,
shipping_option_id: Option<String>,
order_info: Option<OrderInfo>,
telegram_payment_charge_id: String,
provider_payment_charge_id: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OrderInfo {
name: Option<String>,
phone_number: Option<String>,
email: Option<String>,
shipping_address: Option<ShippingAddress>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ShippingAddress {
country_code: String,
state: String,
city: String,
street_line1: String,
street_line2: String,
post_code: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PassportData;
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum ReplyMarkup {
InlineKeyboardMarkup(InlineKeyboardMarkup),
ReplyKeyboardMarkup(ReplyKeyboardMarkup),
ReplyKeyboardRemove(ReplyKeyboardRemove),
ForceReply(ForceReply),
} |
struct Person {
name: String,
age: u8,
}
impl std::fmt::Display for Person {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} is a {} years old human.", self.name, self.age)
}
}
struct Unit;
struct Pair(i32, f32);
fn main() {
let peter_parker = Person {
name: "Peter".to_string(),
age: 27,
};
println!("{}", peter_parker);
let _unit = Unit;
let pair = Pair(1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
|
use crate::{Data, Error, PrefixContext};
use chrono::{TimeZone, Utc};
use sqlx::{pool::PoolConnection, Connection, Sqlite};
use std::{cmp::Reverse, collections::HashMap, env, time::Duration};
const LLVM_MCA_TOOL_ID: &str = "llvm-mcatrunk";
const GODBOLT_TARGETS_URL: &str = "https://godbolt.org/api/compilers/rust";
const ACCEPT_JSON: &str = "application/json";
enum Compilation {
Success {
asm: String,
stderr: String,
llvm_mca: Option<String>,
},
Error {
stderr: String,
},
}
#[derive(Debug, serde::Deserialize)]
struct GodboltOutputSegment {
text: String,
}
#[derive(Debug, serde::Deserialize)]
struct GodboltOutput(Vec<GodboltOutputSegment>);
impl GodboltOutput {
pub fn full_with_ansi_codes_stripped(&self) -> Result<String, Error> {
let mut complete_text = String::new();
for segment in self.0.iter() {
complete_text.push_str(&segment.text);
complete_text.push('\n');
}
Ok(String::from_utf8(strip_ansi_escapes::strip(
complete_text.trim(),
)?)?)
}
}
#[derive(Debug, serde::Deserialize)]
struct GodboltResponse {
code: u8,
stdout: GodboltOutput,
stderr: GodboltOutput,
asm: GodboltOutput,
tools: Vec<GodboltTool>,
}
#[derive(Debug, serde::Deserialize)]
struct GodboltTool {
id: String,
code: u8,
stdout: GodboltOutput,
stderr: GodboltOutput,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct GodboltTarget {
id: String,
name: String,
lang: String,
compiler_type: String,
semver: String,
instruction_set: String,
}
impl GodboltTarget {
fn clean_request_data(&mut self) {
// Some semvers get weird characters like `()` in them or spaces, we strip that out here
self.semver = self
.semver
.chars()
.filter(|char| char.is_alphanumeric() || matches!(char, '.' | '-' | '_'))
.map(|char| char.to_ascii_lowercase())
.collect();
}
}
async fn update_godbolt_targets(
conn: &mut PoolConnection<Sqlite>,
data: &Data,
) -> Result<(), Error> {
// Fetch the last time we updated the targets list, this will be null/none if we've never
// done it before
let last_update_time = sqlx::query!("SELECT last_update FROM last_godbolt_update")
.fetch_optional(&mut *conn)
.await?;
let needs_update = if let Some(last_update_time) = last_update_time {
// Convert the stored timestamp into a utc date time
let last_update_time = Utc.timestamp_nanos(last_update_time.last_update);
// Get the time to wait between each update of the godbolt targets list
let update_period = chrono::Duration::from_std(
env::var("GODBOLT_UPDATE_DURATION")
.ok()
.and_then(|duration| duration.parse::<u64>().ok())
.map(Duration::from_secs)
// Currently set to 12 hours
.unwrap_or_else(|| Duration::from_secs(60 * 60 * 12)),
)?;
let time_since_update = Utc::now().signed_duration_since(last_update_time);
let needs_update = time_since_update >= update_period;
if needs_update {
log::info!(
"godbolt targets were last updated {:#?} ago, updating them",
time_since_update,
);
}
needs_update
} else {
log::info!("godbolt targets haven't yet been updated, fetching them");
true
};
// If we should perform an update then do so
if needs_update {
let request = data
.http
.get(GODBOLT_TARGETS_URL)
.header(reqwest::header::ACCEPT, ACCEPT_JSON)
.build()?;
let mut targets: Vec<GodboltTarget> = data.http.execute(request).await?.json().await?;
log::info!("got {} godbolt targets", targets.len());
// Clean up the data we've gotten from the request
for target in &mut targets {
target.clean_request_data();
}
// Run the target updates within a transaction so that if things go wrong we don't
// end up with an empty targets list
conn.transaction::<_, (), Error>(|conn| {
Box::pin(async move {
// Remove all old values from the targets list, this is probably overly-cautious
// but it at least ensures that we never have incorrect targets within the db
sqlx::query!("DELETE FROM godbolt_targets")
.execute(&mut *conn)
.await?;
// Insert all of our newly fetched targets into the db
for target in targets {
// Some versions have a leading `rustc ` (`rustc beta`, `rustc 1.40.0`, etc.),
// so we strip that here so we only have to do it once
let semver = target
.semver
.strip_prefix("rustc ")
.unwrap_or(&*target.semver);
sqlx::query!(
"INSERT INTO godbolt_targets (
id,
name,
lang,
compiler_type,
semver,
instruction_set
)
VALUES ($1, $2, $3, $4, $5, $6)",
target.id,
target.name,
target.lang,
target.compiler_type,
semver,
target.instruction_set,
)
.execute(&mut *conn)
.await?;
}
// Get the current utc timestamp
let current_time = Utc::now().timestamp_nanos();
// Set the last godbolt update time to now
sqlx::query!(
"INSERT INTO last_godbolt_update (id, last_update)
VALUES (0, $1)
ON CONFLICT(id) DO UPDATE SET last_update = $1
WHERE id = 0",
current_time,
)
.execute(&mut *conn)
.await?;
Ok(())
})
})
.await?;
log::info!("finished updating godbolt targets list");
}
Ok(())
}
async fn fetch_godbolt_targets(data: &Data) -> Result<HashMap<String, String>, Error> {
let mut conn = data.database.acquire().await?;
// If we encounter an error while updating the targets list, just log it
if let Err(error) = update_godbolt_targets(&mut conn, data).await {
log::error!("failed to update godbolt targets list: {:?}", error);
}
log::info!("fetching godbolt targets");
let query = sqlx::query!("SELECT id, semver FROM godbolt_targets")
.fetch_all(&mut conn)
.await?;
let targets: HashMap<_, _> = query
.into_iter()
.map(|target| (target.semver, target.id))
.collect();
log::debug!("fetched {} godbolt targets", targets.len());
Ok(targets)
}
// Transforms human readable rustc version (e.g. "1.34.1") into compiler id on godbolt (e.g. "r1341")
// Full list of version<->id can be obtained at https://godbolt.org/api/compilers/rust
// Ideally we'd also check that the version exists, and give a nice error message if not, but eh.
fn translate_rustc_version<'a>(
version: &str,
targets: &'a HashMap<String, String>,
) -> Result<&'a str, Error> {
if let Some(godbolt_id) = targets.get(version.trim()) {
Ok(godbolt_id)
} else {
Err(
"the `rustc` argument should be a version specifier like `nightly` `beta` or `1.45.2`. \
Run ?targets for a full list"
.into(),
)
}
}
/// Compile a given Rust source code file on Godbolt using the latest nightly compiler with
/// full optimizations (-O3)
/// Returns a multiline string with the pretty printed assembly
async fn compile_rust_source(
http: &reqwest::Client,
targets: &HashMap<String, String>,
source_code: &str,
rustc: &str,
flags: &str,
run_llvm_mca: bool,
) -> Result<Compilation, Error> {
let rustc = translate_rustc_version(rustc, targets)?;
let tools = if run_llvm_mca {
serde_json::json! {
[{"id": LLVM_MCA_TOOL_ID}]
}
} else {
serde_json::json! {
[]
}
};
let request = http
.post(&format!(
"https://godbolt.org/api/compiler/{}/compile",
rustc
))
.header(reqwest::header::ACCEPT, ACCEPT_JSON) // to make godbolt respond in JSON
.json(&serde_json::json! { {
"source": source_code,
"options": {
"userArguments": flags,
"tools": tools,
},
} })
.build()?;
let response: GodboltResponse = http.execute(request).await?.json().await?;
// TODO: use the extract_relevant_lines utility to strip stderr nicely
Ok(if response.code == 0 {
Compilation::Success {
asm: response.asm.full_with_ansi_codes_stripped()?,
stderr: response.stderr.full_with_ansi_codes_stripped()?,
llvm_mca: match response
.tools
.iter()
.find(|tool| tool.id == LLVM_MCA_TOOL_ID)
{
Some(llvm_mca) => Some(llvm_mca.stdout.full_with_ansi_codes_stripped()?),
None => None,
},
}
} else {
Compilation::Error {
stderr: response.stderr.full_with_ansi_codes_stripped()?,
}
})
}
async fn save_to_shortlink(
http: &reqwest::Client,
code: &str,
rustc: &str,
flags: &str,
run_llvm_mca: bool,
) -> Result<String, Error> {
#[derive(serde::Deserialize)]
struct GodboltShortenerResponse {
url: String,
}
let tools = if run_llvm_mca {
serde_json::json! {
[{"id": LLVM_MCA_TOOL_ID}]
}
} else {
serde_json::json! {
[]
}
};
let response = http
.post("https://godbolt.org/api/shortener")
.json(&serde_json::json! { {
"sessions": [{
"language": "rust",
"source": code,
"compilers": [{
"id": rustc,
"options": flags,
"tools": tools,
}],
}]
} })
.send()
.await?;
Ok(response.json::<GodboltShortenerResponse>().await?.url)
}
#[derive(PartialEq, Clone, Copy)]
enum GodboltMode {
Asm,
LlvmIr,
Mca,
}
fn rustc_version_and_flags(params: &poise::KeyValueArgs, mode: GodboltMode) -> (&str, String) {
let rustc = params.get("rustc").unwrap_or("nightly");
let mut flags = params
.get("flags")
.unwrap_or("-Copt-level=3 --edition=2018")
.to_owned();
if mode == GodboltMode::LlvmIr {
flags += " --emit=llvm-ir -Cdebuginfo=0";
}
(rustc, flags)
}
async fn generic_godbolt(
ctx: PrefixContext<'_>,
params: poise::KeyValueArgs,
code: poise::CodeBlock,
mode: GodboltMode,
) -> Result<(), Error> {
let run_llvm_mca = mode == GodboltMode::Mca;
let (rustc, flags) = rustc_version_and_flags(¶ms, mode);
let (lang, text);
let mut note = String::new();
let targets = fetch_godbolt_targets(ctx.data).await?;
let godbolt_result = compile_rust_source(
&ctx.data.http,
&targets,
&code.code,
rustc,
&flags,
run_llvm_mca,
)
.await?;
match godbolt_result {
Compilation::Success {
asm,
stderr,
llvm_mca,
} => {
lang = match mode {
GodboltMode::Asm => "x86asm",
GodboltMode::Mca => "rust",
GodboltMode::LlvmIr => "llvm",
};
text = match mode {
GodboltMode::Mca => {
let llvm_mca = llvm_mca.ok_or("No llvm-mca result was sent by Godbolt")?;
strip_llvm_mca_result(&llvm_mca).to_owned()
}
GodboltMode::Asm | GodboltMode::LlvmIr => asm,
};
if !stderr.is_empty() {
note += "Note: compilation produced warnings\n";
}
}
Compilation::Error { stderr } => {
lang = "rust";
text = stderr;
}
};
if !code.code.contains("pub fn") {
note += "Note: only public functions (`pub fn`) are shown\n";
}
if text.trim().is_empty() {
poise::say_reply(ctx.into(), format!("``` ```{}", note)).await?;
} else {
super::reply_potentially_long_text(
ctx,
&format!("```{}\n{}", lang, text),
&format!("\n```{}", note),
&format!(
"Output too large. Godbolt link: <{}>",
save_to_shortlink(&ctx.data.http, &code.code, rustc, &flags, run_llvm_mca).await?,
),
)
.await?;
}
Ok(())
}
/// View assembly using Godbolt
///
/// Compile Rust code using <https://rust.godbolt.org>. Full optimizations are applied unless \
/// overriden.
/// ```
/// ?godbolt flags={} rustc={} ```
/// pub fn your_function() {
/// // Code
/// }
/// ```
/// ```
/// Optional arguments:
/// - `flags`: flags to pass to rustc invocation. Defaults to `"-Copt-level=3 --edition=2018"`
/// - `rustc`: compiler version to invoke. Defaults to `nightly`. Possible values: `nightly`, `beta` or full version like `1.45.2`
#[poise::command(prefix_command, broadcast_typing, track_edits)]
pub async fn godbolt(
ctx: PrefixContext<'_>,
params: poise::KeyValueArgs,
code: poise::CodeBlock,
) -> Result<(), Error> {
generic_godbolt(ctx, params, code, GodboltMode::Asm).await
}
fn strip_llvm_mca_result(text: &str) -> &str {
text[..text.find("Instruction Info").unwrap_or_else(|| text.len())].trim()
}
/// Used to rank godbolt compiler versions for listing them out
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum SemverRanking<'a> {
Beta,
Nightly,
Compiler(&'a str),
Semver(Reverse<(u16, u16, u16)>),
}
impl<'a> From<&'a str> for SemverRanking<'a> {
fn from(semver: &'a str) -> Self {
match semver {
"beta" => Self::Beta,
"nightly" => Self::Nightly,
semver => {
// Rustc versions are received in a `X.X.X` form, so we parse out
// the major/minor/patch versions and then order them in *reverse*
// order based on their version triple, this means that the most
// recent (read: higher) versions will be at the top of the list
let mut version_triple = semver.splitn(3, '.');
let version_triple = version_triple
.next()
.zip(version_triple.next())
.zip(version_triple.next())
.and_then(|((major, minor), patch)| {
Some((
major.parse().ok()?,
minor.parse().ok()?,
patch.parse().ok()?,
))
});
// If we successfully parsed out a semver tuple, return it
if let Some((major, minor, patch)) = version_triple {
Self::Semver(Reverse((major, minor, patch)))
// Anything that doesn't fit the `X.X.X` format we treat as an alternative
// compiler, we list these after beta & nightly but before the many canonical
// rustc versions
} else {
Self::Compiler(semver)
}
}
}
}
}
/// Lists all available godbolt rustc targets
#[poise::command(prefix_command, broadcast_typing)]
pub async fn targets(ctx: PrefixContext<'_>) -> Result<(), Error> {
let mut conn = ctx.data.database.acquire().await?;
// Attempt to update the godbolt targets list, logging errors if they occur
if let Err(error) = update_godbolt_targets(&mut conn, ctx.data).await {
log::error!("failed to update godbolt targets list: {:?}", error);
}
let mut targets = sqlx::query!("SELECT name, semver, instruction_set FROM godbolt_targets")
.fetch_all(&mut conn)
.await?;
targets.sort_unstable_by(|lhs, rhs| {
SemverRanking::from(&*lhs.semver).cmp(&SemverRanking::from(&*rhs.semver))
});
poise::send_reply(ctx.into(), |msg| {
msg.embed(|embed| {
embed
.title("Godbolt Targets")
.fields(targets.into_iter().map(|target| {
(
target.semver,
format!("{} (runs on {})", target.name, target.instruction_set),
true,
)
}))
})
})
.await?;
Ok(())
}
/// Run performance analysis using llvm-mca
///
/// Run the performance analysis tool llvm-mca using <https://rust.godbolt.org>. Full optimizations \
/// are applied unless overriden.
/// ```
/// ?mca flags={} rustc={} ```
/// pub fn your_function() {
/// // Code
/// }
/// ```
/// ```
/// Optional arguments:
/// - `flags`: flags to pass to rustc invocation. Defaults to `"-Copt-level=3 --edition=2018"`
/// - `rustc`: compiler version to invoke. Defaults to `nightly`. Possible values: `nightly`, `beta` or full version like `1.45.2`
#[poise::command(prefix_command, broadcast_typing, track_edits)]
pub async fn mca(
ctx: PrefixContext<'_>,
params: poise::KeyValueArgs,
code: poise::CodeBlock,
) -> Result<(), Error> {
generic_godbolt(ctx, params, code, GodboltMode::Mca).await
}
/// View LLVM IR using Godbolt
///
/// Compile Rust code using <https://rust.godbolt.org> and emits LLVM IR. Full optimizations \
/// are applied unless overriden.
///
/// Equivalent to ?godbolt but with extra flags `--emit=llvm-ir -Cdebuginfo=0`.
/// ```
/// ?llvmir flags={} rustc={} ```
/// pub fn your_function() {
/// // Code
/// }
/// ```
/// ```
/// Optional arguments:
/// - `flags`: flags to pass to rustc invocation. Defaults to `"-Copt-level=3 --edition=2018"`
/// - `rustc`: compiler version to invoke. Defaults to `nightly`. Possible values: `nightly`, `beta` or full version like `1.45.2`
#[poise::command(prefix_command, broadcast_typing, track_edits)]
pub async fn llvmir(
ctx: PrefixContext<'_>,
params: poise::KeyValueArgs,
code: poise::CodeBlock,
) -> Result<(), Error> {
generic_godbolt(ctx, params, code, GodboltMode::LlvmIr).await
}
// TODO: adjust doc
/// View difference between assembled functions
///
/// Compiles two Rust code snippets using <https://rust.godbolt.org> and diffs them. Full optimizations \
/// are applied unless overriden.
/// ```
/// ?asmdiff flags={} rustc={} ```
/// pub fn foo(x: u32) -> u32 {
/// x
/// }
/// ``` ```
/// pub fn foo(x: u64) -> u64 {
/// x
/// }
/// ```
/// ```
/// Optional arguments:
/// - `flags`: flags to pass to rustc invocation. Defaults to `"-Copt-level=3 --edition=2018"`
/// - `rustc`: compiler version to invoke. Defaults to `nightly`. Possible values: `nightly`, `beta` or full version like `1.45.2`
#[poise::command(prefix_command, broadcast_typing, track_edits, hide_in_help)]
pub async fn asmdiff(
ctx: PrefixContext<'_>,
params: poise::KeyValueArgs,
code1: poise::CodeBlock,
code2: poise::CodeBlock,
) -> Result<(), Error> {
let (rustc, flags) = rustc_version_and_flags(¶ms, GodboltMode::Asm);
let targets = fetch_godbolt_targets(ctx.data).await?;
let (asm1, asm2) = tokio::try_join!(
compile_rust_source(&ctx.data.http, &targets, &code1.code, rustc, &flags, false),
compile_rust_source(&ctx.data.http, &targets, &code2.code, rustc, &flags, false),
)?;
let result = match (asm1, asm2) {
(Compilation::Success { asm: a, .. }, Compilation::Success { asm: b, .. }) => Ok((a, b)),
(Compilation::Error { stderr }, _) => Err(stderr),
(_, Compilation::Error { stderr }) => Err(stderr),
};
match result {
Ok((asm1, asm2)) => {
let mut path1 = std::env::temp_dir();
path1.push("a");
tokio::fs::write(&path1, asm1).await?;
let mut path2 = std::env::temp_dir();
path2.push("b");
tokio::fs::write(&path2, asm2).await?;
let diff = tokio::process::Command::new("git")
.args(&["diff", "--no-index"])
.arg(&path1)
.arg(&path2)
.output()
.await?
.stdout;
super::reply_potentially_long_text(
ctx,
&format!("```diff\n{}", String::from_utf8_lossy(&diff)),
"```",
"(output was truncated)",
)
.await?;
}
Err(stderr) => {
super::reply_potentially_long_text(
ctx,
&format!("```rust\n{}", stderr),
"```",
"(output was truncated)",
)
.await?;
}
}
Ok(())
}
|
#[doc = "Reader of register STATUS"]
pub type R = crate::R<u32, super::STATUS>;
#[doc = "Reader of field `RTC_BUSY`"]
pub type RTC_BUSY_R = crate::R<bool, bool>;
#[doc = "Reader of field `WCO_OK`"]
pub type WCO_OK_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - pending RTC write"]
#[inline(always)]
pub fn rtc_busy(&self) -> RTC_BUSY_R {
RTC_BUSY_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 2 - Indicates that output has transitioned."]
#[inline(always)]
pub fn wco_ok(&self) -> WCO_OK_R {
WCO_OK_R::new(((self.bits >> 2) & 0x01) != 0)
}
}
|
use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin::{self, GlContext};
use gleam::gl;
use std::rc::Rc;
pub struct GlTest {
gl: Rc<gl::Gl>,
}
pub fn load(gl: Rc<gl::Gl>) -> GlTest {
let version = gl.get_string(gl::VERSION);
println!("OpenGL version {}", version);
let vs = gl.create_shader(gl::VERTEX_SHADER);
gl.shader_source(vs, &[VS_SRC]);
gl.compile_shader(vs);
println!("vs status: {}", gl.get_shader_iv(vs, gl::COMPILE_STATUS));
let fs = gl.create_shader(gl::FRAGMENT_SHADER);
gl.shader_source(fs, &[FS_SRC]);
gl.compile_shader(fs);
println!("fs status: {}", gl.get_shader_iv(fs, gl::COMPILE_STATUS));
let program = gl.create_program();
gl.attach_shader(program, vs);
gl.attach_shader(program, fs);
gl.link_program(program);
gl.use_program(program);
// println!("vs status: {:?}", log);
// let log = gl.get_shader_iv(fs, gl::COMPILE_STATUS);
// println!("fs status: {:?}", log);
let vb = gl.gen_buffers(1)[0];
gl.bind_buffer(gl::ARRAY_BUFFER, vb);
gl.buffer_data_untyped(gl::ARRAY_BUFFER,
(VERTEX_DATA.len() * mem::size_of::<f32>()) as gl::types::GLsizeiptr,
VERTEX_DATA.as_ptr() as *const _, gl::STATIC_DRAW);
let vao = gl.gen_vertex_arrays(1)[0];
gl.bind_vertex_array(vao);
let pos_attrib = gl.get_attrib_location(program, "position");
let color_attrib = gl.get_attrib_location(program, "color");
gl.vertex_attrib_pointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, false,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
0);
gl.vertex_attrib_pointer(color_attrib as gl::types::GLuint, 3, gl::FLOAT, false,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
(2 * mem::size_of::<f32>()) as u32);
gl.enable_vertex_attrib_array(pos_attrib as gl::types::GLuint);
gl.enable_vertex_attrib_array(color_attrib as gl::types::GLuint);
GlTest { gl: gl }
}
impl GlTest {
pub fn draw_frame(&self, color: [f32; 4]) {
self.gl.clear_color(color[0], color[1], color[2], color[3]);
self.gl.clear(gl::COLOR_BUFFER_BIT);
self.gl.draw_arrays(gl::TRIANGLES, 0, 3);
// let log = self.gl.get_shader_iv(1, gl::COMPILE_STATUS);
// println!("vs status: {:?}", log);
// let log = self.gl.get_shader_iv(2, gl::COMPILE_STATUS);
// println!("fs status: {:?}", log);
// let log = self.gl.get_shader_info_log(1);
// println!("vs log: {:?}", log);
// let log = self.gl.get_shader_info_log(2);
// println!("fs log: {:?}", log);
}
}
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}";
const FS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
varying vec3 v_color;
void main() {
gl_FragColor = vec4(v_color, 1.0);
}";
|
#[derive(Deserialize, Debug)]
pub struct Meta {
pub total: f64,
}
|
#[doc = "Reader of register MCWDT_MATCH"]
pub type R = crate::R<u32, super::MCWDT_MATCH>;
#[doc = "Writer for register MCWDT_MATCH"]
pub type W = crate::W<u32, super::MCWDT_MATCH>;
#[doc = "Register MCWDT_MATCH `reset()`'s with value 0"]
impl crate::ResetValue for super::MCWDT_MATCH {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `WDT_MATCH0`"]
pub type WDT_MATCH0_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `WDT_MATCH0`"]
pub struct WDT_MATCH0_W<'a> {
w: &'a mut W,
}
impl<'a> WDT_MATCH0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
#[doc = "Reader of field `WDT_MATCH1`"]
pub type WDT_MATCH1_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `WDT_MATCH1`"]
pub struct WDT_MATCH1_W<'a> {
w: &'a mut W,
}
impl<'a> WDT_MATCH1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - Match value for sub-counter 0 of this MCWDT"]
#[inline(always)]
pub fn wdt_match0(&self) -> WDT_MATCH0_R {
WDT_MATCH0_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - Match value for sub-counter 1 of this MCWDT"]
#[inline(always)]
pub fn wdt_match1(&self) -> WDT_MATCH1_R {
WDT_MATCH1_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Match value for sub-counter 0 of this MCWDT"]
#[inline(always)]
pub fn wdt_match0(&mut self) -> WDT_MATCH0_W {
WDT_MATCH0_W { w: self }
}
#[doc = "Bits 16:31 - Match value for sub-counter 1 of this MCWDT"]
#[inline(always)]
pub fn wdt_match1(&mut self) -> WDT_MATCH1_W {
WDT_MATCH1_W { w: self }
}
}
|
use nu_engine::CallExt;
use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
struct Arguments {
radix: Option<Value>,
column_paths: Vec<CellPath>,
little_endian: bool,
}
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"into int"
}
fn signature(&self) -> Signature {
Signature::build("into int")
.named("radix", SyntaxShape::Number, "radix of integer", Some('r'))
.switch("little-endian", "use little-endian byte decoding", None)
.rest(
"rest",
SyntaxShape::CellPath,
"column paths to convert to int (for table input)",
)
.category(Category::Conversions)
}
fn usage(&self) -> &str {
"Convert value to integer"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "natural"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
into_int(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Convert string to integer in table",
example: "echo [[num]; ['-5'] [4] [1.5]] | into int num",
result: None,
},
Example {
description: "Convert string to integer",
example: "'2' | into int",
result: Some(Value::test_int(2)),
},
Example {
description: "Convert decimal to integer",
example: "5.9 | into int",
result: Some(Value::test_int(5)),
},
Example {
description: "Convert decimal string to integer",
example: "'5.9' | into int",
result: Some(Value::test_int(5)),
},
Example {
description: "Convert file size to integer",
example: "4KB | into int",
result: Some(Value::Int {
val: 4000,
span: Span::test_data(),
}),
},
Example {
description: "Convert bool to integer",
example: "[false, true] | into int",
result: Some(Value::List {
vals: vec![Value::test_int(0), Value::test_int(1)],
span: Span::test_data(),
}),
},
Example {
description: "Convert date to integer (Unix timestamp)",
example: "2022-02-02 | into int",
result: Some(Value::test_int(1643760000)),
},
Example {
description: "Convert to integer from binary",
example: "'1101' | into int -r 2",
result: Some(Value::test_int(13)),
},
Example {
description: "Convert to integer from hex",
example: "'FF' | into int -r 16",
result: Some(Value::test_int(255)),
},
Example {
description: "Convert octal string to integer",
example: "'0o10132' | into int",
result: Some(Value::test_int(4186)),
},
Example {
description: "Convert 0 padded string to integer",
example: "'0010132' | into int",
result: Some(Value::test_int(10132)),
},
Example {
description: "Convert 0 padded string to integer with radix",
example: "'0010132' | into int -r 8",
result: Some(Value::test_int(4186)),
},
]
}
}
fn into_int(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let head = call.head;
let options = Arguments {
radix: call.get_flag(engine_state, stack, "radix")?,
little_endian: call.has_flag("little-endian"),
column_paths: call.rest(engine_state, stack, 0)?,
};
let radix: u32 = match options.radix {
Some(Value::Int { val, .. }) => val as u32,
Some(_) => 10,
None => 10,
};
if let Some(val) = &options.radix {
if !(2..=36).contains(&radix) {
return Err(ShellError::UnsupportedInput(
"Radix must lie in the range [2, 36]".to_string(),
val.span()?,
));
}
}
input.map(
move |v| {
if options.column_paths.is_empty() {
action(&v, head, radix, options.little_endian)
} else {
let mut ret = v;
for path in &options.column_paths {
let r = ret.update_cell_path(
&path.members,
Box::new(move |old| action(old, head, radix, options.little_endian)),
);
if let Err(error) = r {
return Value::Error { error };
}
}
ret
}
},
engine_state.ctrlc.clone(),
)
}
pub fn action(input: &Value, span: Span, radix: u32, little_endian: bool) -> Value {
match input {
Value::Int { val: _, .. } => {
if radix == 10 {
input.clone()
} else {
convert_int(input, span, radix)
}
}
Value::Filesize { val, .. } => Value::Int { val: *val, span },
Value::Float { val, .. } => Value::Int {
val: {
if radix == 10 {
*val as i64
} else {
match convert_int(
&Value::Int {
val: *val as i64,
span,
},
span,
radix,
)
.as_i64()
{
Ok(v) => v,
_ => {
return Value::Error {
error: ShellError::UnsupportedInput(
"Could not convert float to integer".to_string(),
span,
),
}
}
}
}
},
span,
},
Value::String { val, .. } => {
if radix == 10 {
match int_from_string(val, span) {
Ok(val) => Value::Int { val, span },
Err(error) => Value::Error { error },
}
} else {
convert_int(input, span, radix)
}
}
Value::Bool { val, .. } => {
if *val {
Value::Int { val: 1, span }
} else {
Value::Int { val: 0, span }
}
}
Value::Date { val, .. } => Value::Int {
val: val.timestamp(),
span,
},
Value::Binary { val, span } => {
use byteorder::{BigEndian, ByteOrder, LittleEndian};
let mut val = val.to_vec();
if little_endian {
while val.len() < 8 {
val.push(0);
}
val.resize(8, 0);
Value::Int {
val: LittleEndian::read_i64(&val),
span: *span,
}
} else {
while val.len() < 8 {
val.insert(0, 0);
}
val.resize(8, 0);
Value::Int {
val: BigEndian::read_i64(&val),
span: *span,
}
}
}
_ => Value::Error {
error: ShellError::UnsupportedInput(
format!("'into int' for unsupported type '{}'", input.get_type()),
span,
),
},
}
}
fn convert_int(input: &Value, head: Span, radix: u32) -> Value {
let i = match input {
Value::Int { val, .. } => val.to_string(),
Value::String { val, .. } => {
let val = val.trim();
if val.starts_with("0x") // hex
|| val.starts_with("0b") // binary
|| val.starts_with("0o")
// octal
{
match int_from_string(val, head) {
Ok(x) => return Value::Int { val: x, span: head },
Err(e) => return Value::Error { error: e },
}
} else if val.starts_with("00") {
// It's a padded string
match i64::from_str_radix(val, radix) {
Ok(n) => return Value::Int { val: n, span: head },
Err(e) => {
return Value::Error {
error: ShellError::CantConvert(
"string".to_string(),
"int".to_string(),
head,
Some(e.to_string()),
),
}
}
}
}
val.to_string()
}
_ => {
return Value::Error {
error: ShellError::UnsupportedInput(
"only strings or integers are supported".to_string(),
head,
),
}
}
};
match i64::from_str_radix(i.trim(), radix) {
Ok(n) => Value::Int { val: n, span: head },
Err(_reason) => Value::Error {
error: ShellError::CantConvert("string".to_string(), "int".to_string(), head, None),
},
}
}
fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
let trimmed = a_string.trim();
match trimmed {
b if b.starts_with("0b") => {
let num = match i64::from_str_radix(b.trim_start_matches("0b"), 2) {
Ok(n) => n,
Err(_reason) => {
return Err(ShellError::CantConvert(
"int".to_string(),
"string".to_string(),
span,
Some(r#"digits following "0b" can only be 0 or 1"#.to_string()),
))
}
};
Ok(num)
}
h if h.starts_with("0x") => {
let num =
match i64::from_str_radix(h.trim_start_matches("0x"), 16) {
Ok(n) => n,
Err(_reason) => return Err(ShellError::CantConvert(
"int".to_string(),
"string".to_string(),
span,
Some(
r#"hexadecimal digits following "0x" should be in 0-9, a-f, or A-F"#
.to_string(),
),
)),
};
Ok(num)
}
o if o.starts_with("0o") => {
let num = match i64::from_str_radix(o.trim_start_matches("0o"), 8) {
Ok(n) => n,
Err(_reason) => {
return Err(ShellError::CantConvert(
"int".to_string(),
"string".to_string(),
span,
Some(r#"octal digits following "0o" should be in 0-7"#.to_string()),
))
}
};
Ok(num)
}
_ => match trimmed.parse::<i64>() {
Ok(n) => Ok(n),
Err(_) => match a_string.parse::<f64>() {
Ok(f) => Ok(f as i64),
_ => Err(ShellError::CantConvert(
"int".to_string(),
"string".to_string(),
span,
Some(format!(
r#"string "{}" does not represent a valid integer"#,
trimmed
)),
)),
},
},
}
}
#[cfg(test)]
mod test {
use super::Value;
use super::*;
use nu_protocol::Type::Error;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
#[test]
fn turns_to_integer() {
let word = Value::test_string("10");
let expected = Value::test_int(10);
let actual = action(&word, Span::test_data(), 10, false);
assert_eq!(actual, expected);
}
#[test]
fn turns_binary_to_integer() {
let s = Value::test_string("0b101");
let actual = action(&s, Span::test_data(), 10, false);
assert_eq!(actual, Value::test_int(5));
}
#[test]
fn turns_hex_to_integer() {
let s = Value::test_string("0xFF");
let actual = action(&s, Span::test_data(), 16, false);
assert_eq!(actual, Value::test_int(255));
}
#[test]
fn communicates_parsing_error_given_an_invalid_integerlike_string() {
let integer_str = Value::test_string("36anra");
let actual = action(&integer_str, Span::test_data(), 10, false);
assert_eq!(actual.get_type(), Error)
}
}
|
use super::*;
pub struct EyeDropper;
impl EyeDropper {
pub fn new() -> Self {
EyeDropper
}
}
impl<N: BaseIntExt, C: Copy + Eq> Tool<N, C> for EyeDropper {
fn press<Ctx: Context<N, C>>(&mut self, p: Point2<N>, ctx: &mut Ctx) {
if let Some(color) = ctx.at(p.x, p.y) {
ctx.change_color(color);
}
}
}
|
use b::b;
use example_crate::a;
fn c() {}
fn main() {
a();
b();
c();
}
|
use prettytable::format::{FormatBuilder, LinePosition, LineSeparator};
pub fn set_table_format(table: &mut prettytable::Table) {
table.set_format(
FormatBuilder::new()
.column_separator('│')
.separator(LinePosition::Top, LineSeparator::new('─', '┬', ' ', ' '))
.separator(LinePosition::Title, LineSeparator::new('─', '┼', ' ', ' '))
.separator(LinePosition::Bottom, LineSeparator::new('─', '┴', ' ', ' '))
.padding(1, 1)
.build(),
);
}
pub mod deque; |
#[doc = "Reader of register CLK_CAL_CNT1"]
pub type R = crate::R<u32, super::CLK_CAL_CNT1>;
#[doc = "Writer for register CLK_CAL_CNT1"]
pub type W = crate::W<u32, super::CLK_CAL_CNT1>;
#[doc = "Register CLK_CAL_CNT1 `reset()`'s with value 0x8000_0000"]
impl crate::ResetValue for super::CLK_CAL_CNT1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x8000_0000
}
}
#[doc = "Reader of field `CAL_COUNTER1`"]
pub type CAL_COUNTER1_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `CAL_COUNTER1`"]
pub struct CAL_COUNTER1_W<'a> {
w: &'a mut W,
}
impl<'a> CAL_COUNTER1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0x00ff_ffff) | ((value as u32) & 0x00ff_ffff);
self.w
}
}
#[doc = "Reader of field `CAL_COUNTER_DONE`"]
pub type CAL_COUNTER_DONE_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:23 - Down-counter clocked on fast DDFT output #0 (see TST_DDFT_FAST_CTL). This register always reads as zero. Counting starts internally when this register is written with a nonzero value. CAL_COUNTER_DONE goes immediately low to indicate that the counter has started and will be asserted when the counters are done. Do not write this field unless CAL_COUNTER_DONE==1."]
#[inline(always)]
pub fn cal_counter1(&self) -> CAL_COUNTER1_R {
CAL_COUNTER1_R::new((self.bits & 0x00ff_ffff) as u32)
}
#[doc = "Bit 31 - Status bit indicating that the internal counter #1 is finished counting and CLK_CAL_CNT2.COUNTER stopped counting up"]
#[inline(always)]
pub fn cal_counter_done(&self) -> CAL_COUNTER_DONE_R {
CAL_COUNTER_DONE_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:23 - Down-counter clocked on fast DDFT output #0 (see TST_DDFT_FAST_CTL). This register always reads as zero. Counting starts internally when this register is written with a nonzero value. CAL_COUNTER_DONE goes immediately low to indicate that the counter has started and will be asserted when the counters are done. Do not write this field unless CAL_COUNTER_DONE==1."]
#[inline(always)]
pub fn cal_counter1(&mut self) -> CAL_COUNTER1_W {
CAL_COUNTER1_W { w: self }
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Certificate {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<certificate::Properties>,
}
pub mod certificate {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "subjectName", default, skip_serializing_if = "Option::is_none")]
pub subject_name: Option<String>,
#[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")]
pub host_names: Vec<String>,
#[serde(rename = "pfxBlob", default, skip_serializing_if = "Option::is_none")]
pub pfx_blob: Option<String>,
#[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")]
pub site_name: Option<String>,
#[serde(rename = "selfLink", default, skip_serializing_if = "Option::is_none")]
pub self_link: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issuer: Option<String>,
#[serde(rename = "issueDate", default, skip_serializing_if = "Option::is_none")]
pub issue_date: Option<String>,
#[serde(rename = "expirationDate", default, skip_serializing_if = "Option::is_none")]
pub expiration_date: Option<String>,
pub password: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
#[serde(rename = "cerBlob", default, skip_serializing_if = "Option::is_none")]
pub cer_blob: Option<String>,
#[serde(rename = "publicKeyHash", default, skip_serializing_if = "Option::is_none")]
pub public_key_hash: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")]
pub key_vault_id: Option<String>,
#[serde(rename = "keyVaultSecretName", default, skip_serializing_if = "Option::is_none")]
pub key_vault_secret_name: Option<String>,
#[serde(rename = "keyVaultSecretStatus", default, skip_serializing_if = "Option::is_none")]
pub key_vault_secret_status: Option<properties::KeyVaultSecretStatus>,
#[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")]
pub geo_region: Option<String>,
#[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")]
pub server_farm_id: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyVaultSecretStatus {
Initialized,
WaitingOnCertificateOrder,
Succeeded,
CertificateOrderFailed,
OperationNotPermittedOnKeyVault,
AzureServiceUnauthorizedToAccessKeyVault,
KeyVaultDoesNotExist,
KeyVaultSecretDoesNotExist,
UnknownError,
ExternalPrivateKey,
Unknown,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCollection {
pub value: Vec<Certificate>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificatePatchResource {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<certificate_patch_resource::Properties>,
}
pub mod certificate_patch_resource {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "subjectName", default, skip_serializing_if = "Option::is_none")]
pub subject_name: Option<String>,
#[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")]
pub host_names: Vec<String>,
#[serde(rename = "pfxBlob", default, skip_serializing_if = "Option::is_none")]
pub pfx_blob: Option<String>,
#[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")]
pub site_name: Option<String>,
#[serde(rename = "selfLink", default, skip_serializing_if = "Option::is_none")]
pub self_link: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub issuer: Option<String>,
#[serde(rename = "issueDate", default, skip_serializing_if = "Option::is_none")]
pub issue_date: Option<String>,
#[serde(rename = "expirationDate", default, skip_serializing_if = "Option::is_none")]
pub expiration_date: Option<String>,
pub password: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
#[serde(rename = "cerBlob", default, skip_serializing_if = "Option::is_none")]
pub cer_blob: Option<String>,
#[serde(rename = "publicKeyHash", default, skip_serializing_if = "Option::is_none")]
pub public_key_hash: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")]
pub key_vault_id: Option<String>,
#[serde(rename = "keyVaultSecretName", default, skip_serializing_if = "Option::is_none")]
pub key_vault_secret_name: Option<String>,
#[serde(rename = "keyVaultSecretStatus", default, skip_serializing_if = "Option::is_none")]
pub key_vault_secret_status: Option<properties::KeyVaultSecretStatus>,
#[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")]
pub geo_region: Option<String>,
#[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")]
pub server_farm_id: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyVaultSecretStatus {
Initialized,
WaitingOnCertificateOrder,
Succeeded,
CertificateOrderFailed,
OperationNotPermittedOnKeyVault,
AzureServiceUnauthorizedToAccessKeyVault,
KeyVaultDoesNotExist,
KeyVaultSecretDoesNotExist,
UnknownError,
ExternalPrivateKey,
Unknown,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApiDefinitionInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceEnvironment {
pub name: String,
pub location: String,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<app_service_environment::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<app_service_environment::Status>,
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(rename = "vnetResourceGroupName", default, skip_serializing_if = "Option::is_none")]
pub vnet_resource_group_name: Option<String>,
#[serde(rename = "vnetSubnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_subnet_name: Option<String>,
#[serde(rename = "virtualNetwork")]
pub virtual_network: VirtualNetworkProfile,
#[serde(rename = "internalLoadBalancingMode", default, skip_serializing_if = "Option::is_none")]
pub internal_load_balancing_mode: Option<app_service_environment::InternalLoadBalancingMode>,
#[serde(rename = "multiSize", default, skip_serializing_if = "Option::is_none")]
pub multi_size: Option<String>,
#[serde(rename = "multiRoleCount", default, skip_serializing_if = "Option::is_none")]
pub multi_role_count: Option<i32>,
#[serde(rename = "workerPools")]
pub worker_pools: Vec<WorkerPool>,
#[serde(rename = "ipsslAddressCount", default, skip_serializing_if = "Option::is_none")]
pub ipssl_address_count: Option<i32>,
#[serde(rename = "databaseEdition", default, skip_serializing_if = "Option::is_none")]
pub database_edition: Option<String>,
#[serde(rename = "databaseServiceObjective", default, skip_serializing_if = "Option::is_none")]
pub database_service_objective: Option<String>,
#[serde(rename = "upgradeDomains", default, skip_serializing_if = "Option::is_none")]
pub upgrade_domains: Option<i32>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "dnsSuffix", default, skip_serializing_if = "Option::is_none")]
pub dns_suffix: Option<String>,
#[serde(rename = "lastAction", default, skip_serializing_if = "Option::is_none")]
pub last_action: Option<String>,
#[serde(rename = "lastActionResult", default, skip_serializing_if = "Option::is_none")]
pub last_action_result: Option<String>,
#[serde(rename = "allowedMultiSizes", default, skip_serializing_if = "Option::is_none")]
pub allowed_multi_sizes: Option<String>,
#[serde(rename = "allowedWorkerSizes", default, skip_serializing_if = "Option::is_none")]
pub allowed_worker_sizes: Option<String>,
#[serde(rename = "maximumNumberOfMachines", default, skip_serializing_if = "Option::is_none")]
pub maximum_number_of_machines: Option<i32>,
#[serde(rename = "vipMappings", default, skip_serializing_if = "Vec::is_empty")]
pub vip_mappings: Vec<VirtualIpMapping>,
#[serde(rename = "environmentCapacities", default, skip_serializing_if = "Vec::is_empty")]
pub environment_capacities: Vec<StampCapacity>,
#[serde(rename = "networkAccessControlList", default, skip_serializing_if = "Vec::is_empty")]
pub network_access_control_list: Vec<NetworkAccessControlEntry>,
#[serde(rename = "environmentIsHealthy", default, skip_serializing_if = "Option::is_none")]
pub environment_is_healthy: Option<bool>,
#[serde(rename = "environmentStatus", default, skip_serializing_if = "Option::is_none")]
pub environment_status: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "frontEndScaleFactor", default, skip_serializing_if = "Option::is_none")]
pub front_end_scale_factor: Option<i32>,
#[serde(rename = "defaultFrontEndScaleFactor", default, skip_serializing_if = "Option::is_none")]
pub default_front_end_scale_factor: Option<i32>,
#[serde(rename = "apiManagementAccountId", default, skip_serializing_if = "Option::is_none")]
pub api_management_account_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspended: Option<bool>,
#[serde(rename = "dynamicCacheEnabled", default, skip_serializing_if = "Option::is_none")]
pub dynamic_cache_enabled: Option<bool>,
#[serde(rename = "clusterSettings", default, skip_serializing_if = "Vec::is_empty")]
pub cluster_settings: Vec<NameValuePair>,
#[serde(rename = "userWhitelistedIpRanges", default, skip_serializing_if = "Vec::is_empty")]
pub user_whitelisted_ip_ranges: Vec<String>,
}
pub mod app_service_environment {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Canceled,
InProgress,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Preparing,
Ready,
Scaling,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum InternalLoadBalancingMode {
None,
Web,
Publishing,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServicePlan {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<app_service_plan::Properties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<SkuDescription>,
}
pub mod app_service_plan {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
pub name: String,
#[serde(rename = "workerTierName", default, skip_serializing_if = "Option::is_none")]
pub worker_tier_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<properties::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subscription: Option<String>,
#[serde(rename = "adminSiteName", default, skip_serializing_if = "Option::is_none")]
pub admin_site_name: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "maximumNumberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub maximum_number_of_workers: Option<i32>,
#[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")]
pub geo_region: Option<String>,
#[serde(rename = "perSiteScaling", default, skip_serializing_if = "Option::is_none")]
pub per_site_scaling: Option<bool>,
#[serde(rename = "numberOfSites", default, skip_serializing_if = "Option::is_none")]
pub number_of_sites: Option<i32>,
#[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")]
pub is_spot: Option<bool>,
#[serde(rename = "spotExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub spot_expiration_time: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reserved: Option<bool>,
#[serde(rename = "targetWorkerCount", default, skip_serializing_if = "Option::is_none")]
pub target_worker_count: Option<i32>,
#[serde(rename = "targetWorkerSizeId", default, skip_serializing_if = "Option::is_none")]
pub target_worker_size_id: Option<i32>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<properties::ProvisioningState>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Ready,
Pending,
Creating,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Failed,
Canceled,
InProgress,
Deleting,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServicePlanCollection {
pub value: Vec<AppServicePlan>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealActions {
#[serde(rename = "actionType", default, skip_serializing_if = "Option::is_none")]
pub action_type: Option<auto_heal_actions::ActionType>,
#[serde(rename = "customAction", default, skip_serializing_if = "Option::is_none")]
pub custom_action: Option<AutoHealCustomAction>,
#[serde(rename = "minProcessExecutionTime", default, skip_serializing_if = "Option::is_none")]
pub min_process_execution_time: Option<String>,
}
pub mod auto_heal_actions {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ActionType {
Recycle,
LogEvent,
CustomAction,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealCustomAction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exe: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealRules {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub triggers: Option<AutoHealTriggers>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actions: Option<AutoHealActions>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoHealTriggers {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requests: Option<RequestsBasedTrigger>,
#[serde(rename = "privateBytesInKB", default, skip_serializing_if = "Option::is_none")]
pub private_bytes_in_kb: Option<i32>,
#[serde(rename = "statusCodes", default, skip_serializing_if = "Vec::is_empty")]
pub status_codes: Vec<StatusCodesBasedTrigger>,
#[serde(rename = "slowRequests", default, skip_serializing_if = "Option::is_none")]
pub slow_requests: Option<SlowRequestsBasedTrigger>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Capability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloningInfo {
#[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")]
pub correlation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub overwrite: Option<bool>,
#[serde(rename = "cloneCustomHostNames", default, skip_serializing_if = "Option::is_none")]
pub clone_custom_host_names: Option<bool>,
#[serde(rename = "cloneSourceControl", default, skip_serializing_if = "Option::is_none")]
pub clone_source_control: Option<bool>,
#[serde(rename = "sourceWebAppId")]
pub source_web_app_id: String,
#[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment: Option<String>,
#[serde(rename = "appSettingsOverrides", default, skip_serializing_if = "Option::is_none")]
pub app_settings_overrides: Option<serde_json::Value>,
#[serde(rename = "configureLoadBalancing", default, skip_serializing_if = "Option::is_none")]
pub configure_load_balancing: Option<bool>,
#[serde(rename = "trafficManagerProfileId", default, skip_serializing_if = "Option::is_none")]
pub traffic_manager_profile_id: Option<String>,
#[serde(rename = "trafficManagerProfileName", default, skip_serializing_if = "Option::is_none")]
pub traffic_manager_profile_name: Option<String>,
#[serde(rename = "ignoreQuotas", default, skip_serializing_if = "Option::is_none")]
pub ignore_quotas: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConnStringInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")]
pub connection_string: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<conn_string_info::Type>,
}
pub mod conn_string_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
MySql,
#[serde(rename = "SQLServer")]
SqlServer,
#[serde(rename = "SQLAzure")]
SqlAzure,
Custom,
NotificationHub,
ServiceBus,
EventHub,
ApiHub,
DocDb,
RedisCache,
#[serde(rename = "PostgreSQL")]
PostgreSql,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CorsSettings {
#[serde(rename = "allowedOrigins", default, skip_serializing_if = "Vec::is_empty")]
pub allowed_origins: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmOperationCollection {
pub value: Vec<CsmOperationDescription>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmOperationDescription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<CsmOperationDisplay>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CsmOperationDescriptionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmOperationDescriptionProperties {
#[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")]
pub service_specification: Option<ServiceSpecification>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmOperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmUsageQuota {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "nextResetTime", default, skip_serializing_if = "Option::is_none")]
pub next_reset_time: Option<String>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<LocalizableString>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmUsageQuotaCollection {
pub value: Vec<CsmUsageQuota>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Dimension {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "internalName", default, skip_serializing_if = "Option::is_none")]
pub internal_name: Option<String>,
#[serde(rename = "toBeExportedForShoebox", default, skip_serializing_if = "Option::is_none")]
pub to_be_exported_for_shoebox: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorEntity {
#[serde(rename = "extendedCode", default, skip_serializing_if = "Option::is_none")]
pub extended_code: Option<String>,
#[serde(rename = "messageTemplate", default, skip_serializing_if = "Option::is_none")]
pub message_template: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub parameters: Vec<String>,
#[serde(rename = "innerErrors", default, skip_serializing_if = "Vec::is_empty")]
pub inner_errors: Vec<ErrorEntity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DefaultErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<default_error_response::Error>,
}
pub mod default_error_response {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Error {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub innererror: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Experiments {
#[serde(rename = "rampUpRules", default, skip_serializing_if = "Vec::is_empty")]
pub ramp_up_rules: Vec<RampUpRule>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HandlerMapping {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extension: Option<String>,
#[serde(rename = "scriptProcessor", default, skip_serializing_if = "Option::is_none")]
pub script_processor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub arguments: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostNameSslState {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "sslState", default, skip_serializing_if = "Option::is_none")]
pub ssl_state: Option<host_name_ssl_state::SslState>,
#[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")]
pub virtual_ip: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(rename = "toUpdate", default, skip_serializing_if = "Option::is_none")]
pub to_update: Option<bool>,
#[serde(rename = "hostType", default, skip_serializing_if = "Option::is_none")]
pub host_type: Option<host_name_ssl_state::HostType>,
}
pub mod host_name_ssl_state {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SslState {
Disabled,
SniEnabled,
IpBasedEnabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HostType {
Standard,
Repository,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostingEnvironmentProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnection {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<hybrid_connection::Properties>,
}
pub mod hybrid_connection {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "serviceBusNamespace", default, skip_serializing_if = "Option::is_none")]
pub service_bus_namespace: Option<String>,
#[serde(rename = "relayName", default, skip_serializing_if = "Option::is_none")]
pub relay_name: Option<String>,
#[serde(rename = "relayArmUri", default, skip_serializing_if = "Option::is_none")]
pub relay_arm_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hostname: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<i32>,
#[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")]
pub send_key_name: Option<String>,
#[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")]
pub send_key_value: Option<String>,
#[serde(rename = "serviceBusSuffix", default, skip_serializing_if = "Option::is_none")]
pub service_bus_suffix: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HybridConnectionKey {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<hybrid_connection_key::Properties>,
}
pub mod hybrid_connection_key {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")]
pub send_key_name: Option<String>,
#[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")]
pub send_key_value: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Identifier {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<identifier::Properties>,
}
pub mod identifier {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IdentifierCollection {
pub value: Vec<Identifier>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IpSecurityRestriction {
#[serde(rename = "ipAddress")]
pub ip_address: String,
#[serde(rename = "subnetMask", default, skip_serializing_if = "Option::is_none")]
pub subnet_mask: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedServiceIdentity {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<managed_service_identity::Type>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
}
pub mod managed_service_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricAvailability {
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")]
pub blob_duration: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricSpecification {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")]
pub display_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")]
pub aggregation_type: Option<String>,
#[serde(rename = "supportsInstanceLevelAggregation", default, skip_serializing_if = "Option::is_none")]
pub supports_instance_level_aggregation: Option<bool>,
#[serde(rename = "enableRegionalMdmAccount", default, skip_serializing_if = "Option::is_none")]
pub enable_regional_mdm_account: Option<bool>,
#[serde(rename = "sourceMdmAccount", default, skip_serializing_if = "Option::is_none")]
pub source_mdm_account: Option<String>,
#[serde(rename = "sourceMdmNamespace", default, skip_serializing_if = "Option::is_none")]
pub source_mdm_namespace: Option<String>,
#[serde(rename = "metricFilterPattern", default, skip_serializing_if = "Option::is_none")]
pub metric_filter_pattern: Option<String>,
#[serde(rename = "fillGapWithZero", default, skip_serializing_if = "Option::is_none")]
pub fill_gap_with_zero: Option<bool>,
#[serde(rename = "isInternal", default, skip_serializing_if = "Option::is_none")]
pub is_internal: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dimensions: Vec<Dimension>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub availabilities: Vec<MetricAvailability>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameIdentifier {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameValuePair {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkAccessControlEntry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<network_access_control_entry::Action>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option<i32>,
#[serde(rename = "remoteSubnet", default, skip_serializing_if = "Option::is_none")]
pub remote_subnet: Option<String>,
}
pub mod network_access_control_entry {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Action {
Permit,
Deny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<operation::Status>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<ErrorEntity>,
#[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")]
pub created_time: Option<String>,
#[serde(rename = "modifiedTime", default, skip_serializing_if = "Option::is_none")]
pub modified_time: Option<String>,
#[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")]
pub expiration_time: Option<String>,
#[serde(rename = "geoMasterOperationId", default, skip_serializing_if = "Option::is_none")]
pub geo_master_operation_id: Option<String>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
InProgress,
Failed,
Succeeded,
TimedOut,
Created,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyOnlyResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PushSettings {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<push_settings::Properties>,
}
pub mod push_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "isPushEnabled")]
pub is_push_enabled: bool,
#[serde(rename = "tagWhitelistJson", default, skip_serializing_if = "Option::is_none")]
pub tag_whitelist_json: Option<String>,
#[serde(rename = "tagsRequiringAuth", default, skip_serializing_if = "Option::is_none")]
pub tags_requiring_auth: Option<String>,
#[serde(rename = "dynamicTagsJson", default, skip_serializing_if = "Option::is_none")]
pub dynamic_tags_json: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RampUpRule {
#[serde(rename = "actionHostName", default, skip_serializing_if = "Option::is_none")]
pub action_host_name: Option<String>,
#[serde(rename = "reroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub reroute_percentage: Option<f64>,
#[serde(rename = "changeStep", default, skip_serializing_if = "Option::is_none")]
pub change_step: Option<f64>,
#[serde(rename = "changeIntervalInMinutes", default, skip_serializing_if = "Option::is_none")]
pub change_interval_in_minutes: Option<i32>,
#[serde(rename = "minReroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub min_reroute_percentage: Option<f64>,
#[serde(rename = "maxReroutePercentage", default, skip_serializing_if = "Option::is_none")]
pub max_reroute_percentage: Option<f64>,
#[serde(rename = "changeDecisionCallbackUrl", default, skip_serializing_if = "Option::is_none")]
pub change_decision_callback_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RequestsBasedTrigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
pub location: String,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetric {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<ResourceMetricName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "metricValues", default, skip_serializing_if = "Vec::is_empty")]
pub metric_values: Vec<ResourceMetricValue>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub properties: Vec<ResourceMetricProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricAvailability {
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricCollection {
pub value: Vec<ResourceMetric>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricDefinition {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<resource_metric_definition::Properties>,
}
pub mod resource_metric_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<ResourceMetricName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "primaryAggregationType", default, skip_serializing_if = "Option::is_none")]
pub primary_aggregation_type: Option<String>,
#[serde(rename = "metricAvailabilities", default, skip_serializing_if = "Vec::is_empty")]
pub metric_availabilities: Vec<ResourceMetricAvailability>,
#[serde(rename = "resourceUri", default, skip_serializing_if = "Option::is_none")]
pub resource_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricDefinitionCollection {
pub value: Vec<ResourceMetricDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricName {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceMetricValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub average: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<f32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub properties: Vec<ResourceMetricProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceSpecification {
#[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")]
pub metric_specifications: Vec<MetricSpecification>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Site {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<site::Properties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ManagedServiceIdentity>,
}
pub mod site {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")]
pub host_names: Vec<String>,
#[serde(rename = "repositorySiteName", default, skip_serializing_if = "Option::is_none")]
pub repository_site_name: Option<String>,
#[serde(rename = "usageState", default, skip_serializing_if = "Option::is_none")]
pub usage_state: Option<properties::UsageState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(rename = "enabledHostNames", default, skip_serializing_if = "Vec::is_empty")]
pub enabled_host_names: Vec<String>,
#[serde(rename = "availabilityState", default, skip_serializing_if = "Option::is_none")]
pub availability_state: Option<properties::AvailabilityState>,
#[serde(rename = "hostNameSslStates", default, skip_serializing_if = "Vec::is_empty")]
pub host_name_ssl_states: Vec<HostNameSslState>,
#[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")]
pub server_farm_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reserved: Option<bool>,
#[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")]
pub last_modified_time_utc: Option<String>,
#[serde(rename = "siteConfig", default, skip_serializing_if = "Option::is_none")]
pub site_config: Option<SiteConfig>,
#[serde(rename = "trafficManagerHostNames", default, skip_serializing_if = "Vec::is_empty")]
pub traffic_manager_host_names: Vec<String>,
#[serde(rename = "scmSiteAlsoStopped", default, skip_serializing_if = "Option::is_none")]
pub scm_site_also_stopped: Option<bool>,
#[serde(rename = "targetSwapSlot", default, skip_serializing_if = "Option::is_none")]
pub target_swap_slot: Option<String>,
#[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment_profile: Option<HostingEnvironmentProfile>,
#[serde(rename = "clientAffinityEnabled", default, skip_serializing_if = "Option::is_none")]
pub client_affinity_enabled: Option<bool>,
#[serde(rename = "clientCertEnabled", default, skip_serializing_if = "Option::is_none")]
pub client_cert_enabled: Option<bool>,
#[serde(rename = "hostNamesDisabled", default, skip_serializing_if = "Option::is_none")]
pub host_names_disabled: Option<bool>,
#[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Option::is_none")]
pub outbound_ip_addresses: Option<String>,
#[serde(rename = "possibleOutboundIpAddresses", default, skip_serializing_if = "Option::is_none")]
pub possible_outbound_ip_addresses: Option<String>,
#[serde(rename = "containerSize", default, skip_serializing_if = "Option::is_none")]
pub container_size: Option<i32>,
#[serde(rename = "dailyMemoryTimeQuota", default, skip_serializing_if = "Option::is_none")]
pub daily_memory_time_quota: Option<i32>,
#[serde(rename = "suspendedTill", default, skip_serializing_if = "Option::is_none")]
pub suspended_till: Option<String>,
#[serde(rename = "maxNumberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub max_number_of_workers: Option<i32>,
#[serde(rename = "cloningInfo", default, skip_serializing_if = "Option::is_none")]
pub cloning_info: Option<CloningInfo>,
#[serde(rename = "snapshotInfo", default, skip_serializing_if = "Option::is_none")]
pub snapshot_info: Option<SnapshotRecoveryRequest>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "isDefaultContainer", default, skip_serializing_if = "Option::is_none")]
pub is_default_container: Option<bool>,
#[serde(rename = "defaultHostName", default, skip_serializing_if = "Option::is_none")]
pub default_host_name: Option<String>,
#[serde(rename = "slotSwapStatus", default, skip_serializing_if = "Option::is_none")]
pub slot_swap_status: Option<SlotSwapStatus>,
#[serde(rename = "httpsOnly", default, skip_serializing_if = "Option::is_none")]
pub https_only: Option<bool>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum UsageState {
Normal,
Exceeded,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AvailabilityState {
Normal,
Limited,
DisasterRecoveryMode,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteConfig {
#[serde(rename = "numberOfWorkers", default, skip_serializing_if = "Option::is_none")]
pub number_of_workers: Option<i32>,
#[serde(rename = "defaultDocuments", default, skip_serializing_if = "Vec::is_empty")]
pub default_documents: Vec<String>,
#[serde(rename = "netFrameworkVersion", default, skip_serializing_if = "Option::is_none")]
pub net_framework_version: Option<String>,
#[serde(rename = "phpVersion", default, skip_serializing_if = "Option::is_none")]
pub php_version: Option<String>,
#[serde(rename = "pythonVersion", default, skip_serializing_if = "Option::is_none")]
pub python_version: Option<String>,
#[serde(rename = "nodeVersion", default, skip_serializing_if = "Option::is_none")]
pub node_version: Option<String>,
#[serde(rename = "linuxFxVersion", default, skip_serializing_if = "Option::is_none")]
pub linux_fx_version: Option<String>,
#[serde(rename = "requestTracingEnabled", default, skip_serializing_if = "Option::is_none")]
pub request_tracing_enabled: Option<bool>,
#[serde(rename = "requestTracingExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub request_tracing_expiration_time: Option<String>,
#[serde(rename = "remoteDebuggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub remote_debugging_enabled: Option<bool>,
#[serde(rename = "remoteDebuggingVersion", default, skip_serializing_if = "Option::is_none")]
pub remote_debugging_version: Option<String>,
#[serde(rename = "httpLoggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub http_logging_enabled: Option<bool>,
#[serde(rename = "logsDirectorySizeLimit", default, skip_serializing_if = "Option::is_none")]
pub logs_directory_size_limit: Option<i32>,
#[serde(rename = "detailedErrorLoggingEnabled", default, skip_serializing_if = "Option::is_none")]
pub detailed_error_logging_enabled: Option<bool>,
#[serde(rename = "publishingUsername", default, skip_serializing_if = "Option::is_none")]
pub publishing_username: Option<String>,
#[serde(rename = "appSettings", default, skip_serializing_if = "Vec::is_empty")]
pub app_settings: Vec<NameValuePair>,
#[serde(rename = "connectionStrings", default, skip_serializing_if = "Vec::is_empty")]
pub connection_strings: Vec<ConnStringInfo>,
#[serde(rename = "machineKey", default, skip_serializing_if = "Option::is_none")]
pub machine_key: Option<SiteMachineKey>,
#[serde(rename = "handlerMappings", default, skip_serializing_if = "Vec::is_empty")]
pub handler_mappings: Vec<HandlerMapping>,
#[serde(rename = "documentRoot", default, skip_serializing_if = "Option::is_none")]
pub document_root: Option<String>,
#[serde(rename = "scmType", default, skip_serializing_if = "Option::is_none")]
pub scm_type: Option<site_config::ScmType>,
#[serde(rename = "use32BitWorkerProcess", default, skip_serializing_if = "Option::is_none")]
pub use32_bit_worker_process: Option<bool>,
#[serde(rename = "webSocketsEnabled", default, skip_serializing_if = "Option::is_none")]
pub web_sockets_enabled: Option<bool>,
#[serde(rename = "alwaysOn", default, skip_serializing_if = "Option::is_none")]
pub always_on: Option<bool>,
#[serde(rename = "javaVersion", default, skip_serializing_if = "Option::is_none")]
pub java_version: Option<String>,
#[serde(rename = "javaContainer", default, skip_serializing_if = "Option::is_none")]
pub java_container: Option<String>,
#[serde(rename = "javaContainerVersion", default, skip_serializing_if = "Option::is_none")]
pub java_container_version: Option<String>,
#[serde(rename = "appCommandLine", default, skip_serializing_if = "Option::is_none")]
pub app_command_line: Option<String>,
#[serde(rename = "managedPipelineMode", default, skip_serializing_if = "Option::is_none")]
pub managed_pipeline_mode: Option<site_config::ManagedPipelineMode>,
#[serde(rename = "virtualApplications", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_applications: Vec<VirtualApplication>,
#[serde(rename = "loadBalancing", default, skip_serializing_if = "Option::is_none")]
pub load_balancing: Option<site_config::LoadBalancing>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub experiments: Option<Experiments>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limits: Option<SiteLimits>,
#[serde(rename = "autoHealEnabled", default, skip_serializing_if = "Option::is_none")]
pub auto_heal_enabled: Option<bool>,
#[serde(rename = "autoHealRules", default, skip_serializing_if = "Option::is_none")]
pub auto_heal_rules: Option<AutoHealRules>,
#[serde(rename = "tracingOptions", default, skip_serializing_if = "Option::is_none")]
pub tracing_options: Option<String>,
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cors: Option<CorsSettings>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub push: Option<PushSettings>,
#[serde(rename = "apiDefinition", default, skip_serializing_if = "Option::is_none")]
pub api_definition: Option<ApiDefinitionInfo>,
#[serde(rename = "autoSwapSlotName", default, skip_serializing_if = "Option::is_none")]
pub auto_swap_slot_name: Option<String>,
#[serde(rename = "localMySqlEnabled", default, skip_serializing_if = "Option::is_none")]
pub local_my_sql_enabled: Option<bool>,
#[serde(rename = "ipSecurityRestrictions", default, skip_serializing_if = "Vec::is_empty")]
pub ip_security_restrictions: Vec<IpSecurityRestriction>,
#[serde(rename = "http20Enabled", default, skip_serializing_if = "Option::is_none")]
pub http20_enabled: Option<bool>,
#[serde(rename = "minTlsVersion", default, skip_serializing_if = "Option::is_none")]
pub min_tls_version: Option<site_config::MinTlsVersion>,
}
pub mod site_config {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScmType {
None,
Dropbox,
Tfs,
LocalGit,
GitHub,
CodePlexGit,
CodePlexHg,
BitbucketGit,
BitbucketHg,
ExternalGit,
ExternalHg,
OneDrive,
#[serde(rename = "VSO")]
Vso,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ManagedPipelineMode {
Integrated,
Classic,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LoadBalancing {
WeightedRoundRobin,
LeastRequests,
LeastResponseTime,
WeightedTotalTraffic,
RequestHash,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MinTlsVersion {
#[serde(rename = "1.0")]
N1_0,
#[serde(rename = "1.1")]
N1_1,
#[serde(rename = "1.2")]
N1_2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteLimits {
#[serde(rename = "maxPercentageCpu", default, skip_serializing_if = "Option::is_none")]
pub max_percentage_cpu: Option<f64>,
#[serde(rename = "maxMemoryInMb", default, skip_serializing_if = "Option::is_none")]
pub max_memory_in_mb: Option<i64>,
#[serde(rename = "maxDiskSizeInMb", default, skip_serializing_if = "Option::is_none")]
pub max_disk_size_in_mb: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SiteMachineKey {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validation: Option<String>,
#[serde(rename = "validationKey", default, skip_serializing_if = "Option::is_none")]
pub validation_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decryption: Option<String>,
#[serde(rename = "decryptionKey", default, skip_serializing_if = "Option::is_none")]
pub decryption_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuCapacity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<i32>,
#[serde(rename = "scaleType", default, skip_serializing_if = "Option::is_none")]
pub scale_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuDescription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<i32>,
#[serde(rename = "skuCapacity", default, skip_serializing_if = "Option::is_none")]
pub sku_capacity: Option<SkuCapacity>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<Capability>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SlotSwapStatus {
#[serde(rename = "timestampUtc", default, skip_serializing_if = "Option::is_none")]
pub timestamp_utc: Option<String>,
#[serde(rename = "sourceSlotName", default, skip_serializing_if = "Option::is_none")]
pub source_slot_name: Option<String>,
#[serde(rename = "destinationSlotName", default, skip_serializing_if = "Option::is_none")]
pub destination_slot_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SlowRequestsBasedTrigger {
#[serde(rename = "timeTaken", default, skip_serializing_if = "Option::is_none")]
pub time_taken: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotRecoveryRequest {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<snapshot_recovery_request::Properties>,
}
pub mod snapshot_recovery_request {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "snapshotTime", default, skip_serializing_if = "Option::is_none")]
pub snapshot_time: Option<String>,
#[serde(rename = "recoveryTarget", default, skip_serializing_if = "Option::is_none")]
pub recovery_target: Option<SnapshotRecoveryTarget>,
pub overwrite: bool,
#[serde(rename = "recoverConfiguration", default, skip_serializing_if = "Option::is_none")]
pub recover_configuration: Option<bool>,
#[serde(rename = "ignoreConflictingHostNames", default, skip_serializing_if = "Option::is_none")]
pub ignore_conflicting_host_names: Option<bool>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotRecoveryTarget {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StampCapacity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "availableCapacity", default, skip_serializing_if = "Option::is_none")]
pub available_capacity: Option<i64>,
#[serde(rename = "totalCapacity", default, skip_serializing_if = "Option::is_none")]
pub total_capacity: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")]
pub compute_mode: Option<stamp_capacity::ComputeMode>,
#[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")]
pub worker_size: Option<stamp_capacity::WorkerSize>,
#[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")]
pub worker_size_id: Option<i32>,
#[serde(rename = "excludeFromCapacityAllocation", default, skip_serializing_if = "Option::is_none")]
pub exclude_from_capacity_allocation: Option<bool>,
#[serde(rename = "isApplicableForAllComputeModes", default, skip_serializing_if = "Option::is_none")]
pub is_applicable_for_all_compute_modes: Option<bool>,
#[serde(rename = "siteMode", default, skip_serializing_if = "Option::is_none")]
pub site_mode: Option<String>,
}
pub mod stamp_capacity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeMode {
Shared,
Dedicated,
Dynamic,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WorkerSize {
Default,
Small,
Medium,
Large,
D1,
D2,
D3,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatusCodesBasedTrigger {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<i32>,
#[serde(rename = "subStatus", default, skip_serializing_if = "Option::is_none")]
pub sub_status: Option<i32>,
#[serde(rename = "win32Status", default, skip_serializing_if = "Option::is_none")]
pub win32_status: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")]
pub time_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct User {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<user::Properties>,
}
pub mod user {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "publishingUserName")]
pub publishing_user_name: String,
#[serde(rename = "publishingPassword", default, skip_serializing_if = "Option::is_none")]
pub publishing_password: Option<String>,
#[serde(rename = "publishingPasswordHash", default, skip_serializing_if = "Option::is_none")]
pub publishing_password_hash: Option<String>,
#[serde(rename = "publishingPasswordHashSalt", default, skip_serializing_if = "Option::is_none")]
pub publishing_password_hash_salt: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualApplication {
#[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")]
pub virtual_path: Option<String>,
#[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")]
pub physical_path: Option<String>,
#[serde(rename = "preloadEnabled", default, skip_serializing_if = "Option::is_none")]
pub preload_enabled: Option<bool>,
#[serde(rename = "virtualDirectories", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_directories: Vec<VirtualDirectory>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualDirectory {
#[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")]
pub virtual_path: Option<String>,
#[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")]
pub physical_path: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualIpMapping {
#[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")]
pub virtual_ip: Option<String>,
#[serde(rename = "internalHttpPort", default, skip_serializing_if = "Option::is_none")]
pub internal_http_port: Option<i32>,
#[serde(rename = "internalHttpsPort", default, skip_serializing_if = "Option::is_none")]
pub internal_https_port: Option<i32>,
#[serde(rename = "inUse", default, skip_serializing_if = "Option::is_none")]
pub in_use: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subnet: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetGateway {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_gateway::Properties>,
}
pub mod vnet_gateway {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(rename = "vpnPackageUri")]
pub vpn_package_uri: String,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetInfo {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_info::Properties>,
}
pub mod vnet_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "vnetResourceId", default, skip_serializing_if = "Option::is_none")]
pub vnet_resource_id: Option<String>,
#[serde(rename = "certThumbprint", default, skip_serializing_if = "Option::is_none")]
pub cert_thumbprint: Option<String>,
#[serde(rename = "certBlob", default, skip_serializing_if = "Option::is_none")]
pub cert_blob: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub routes: Vec<VnetRoute>,
#[serde(rename = "resyncRequired", default, skip_serializing_if = "Option::is_none")]
pub resync_required: Option<bool>,
#[serde(rename = "dnsServers", default, skip_serializing_if = "Option::is_none")]
pub dns_servers: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetRoute {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_route::Properties>,
}
pub mod vnet_route {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "startAddress", default, skip_serializing_if = "Option::is_none")]
pub start_address: Option<String>,
#[serde(rename = "endAddress", default, skip_serializing_if = "Option::is_none")]
pub end_address: Option<String>,
#[serde(rename = "routeType", default, skip_serializing_if = "Option::is_none")]
pub route_type: Option<properties::RouteType>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RouteType {
#[serde(rename = "DEFAULT")]
Default,
#[serde(rename = "INHERITED")]
Inherited,
#[serde(rename = "STATIC")]
Static,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebAppCollection {
pub value: Vec<Site>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkerPool {
#[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")]
pub worker_size_id: Option<i32>,
#[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")]
pub compute_mode: Option<worker_pool::ComputeMode>,
#[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")]
pub worker_size: Option<String>,
#[serde(rename = "workerCount", default, skip_serializing_if = "Option::is_none")]
pub worker_count: Option<i32>,
#[serde(rename = "instanceNames", default, skip_serializing_if = "Vec::is_empty")]
pub instance_names: Vec<String>,
}
pub mod worker_pool {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeMode {
Shared,
Dedicated,
Dynamic,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedSite {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<i32>,
#[serde(rename = "deletedTimestamp", default, skip_serializing_if = "Option::is_none")]
pub deleted_timestamp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subscription: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slot: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeletedWebAppCollection {
pub value: Vec<DeletedSite>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AbnormalTimePeriod {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<DetectorAbnormalTimePeriod>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<Solution>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnalysisData {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(rename = "detectorDefinition", default, skip_serializing_if = "Option::is_none")]
pub detector_definition: Option<DetectorDefinition>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metrics: Vec<DiagnosticMetricSet>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub data: Vec<Vec<NameValuePair>>,
#[serde(rename = "detectorMetaData", default, skip_serializing_if = "Option::is_none")]
pub detector_meta_data: Option<ResponseMetaData>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnalysisDefinition {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<analysis_definition::Properties>,
}
pub mod analysis_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataSource {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub instructions: Vec<String>,
#[serde(rename = "dataSourceUri", default, skip_serializing_if = "Vec::is_empty")]
pub data_source_uri: Vec<NameValuePair>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataTableResponseColumn {
#[serde(rename = "columnName", default, skip_serializing_if = "Option::is_none")]
pub column_name: Option<String>,
#[serde(rename = "dataType", default, skip_serializing_if = "Option::is_none")]
pub data_type: Option<String>,
#[serde(rename = "columnType", default, skip_serializing_if = "Option::is_none")]
pub column_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataTableResponseObject {
#[serde(rename = "tableName", default, skip_serializing_if = "Option::is_none")]
pub table_name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub columns: Vec<DataTableResponseColumn>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rows: Vec<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetectorAbnormalTimePeriod {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<f64>,
#[serde(rename = "metaData", default, skip_serializing_if = "Vec::is_empty")]
pub meta_data: Vec<Vec<NameValuePair>>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<detector_abnormal_time_period::Type>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub solutions: Vec<Solution>,
}
pub mod detector_abnormal_time_period {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
ServiceIncident,
AppDeployment,
AppCrash,
RuntimeIssueDetected,
AseDeployment,
UserIssue,
PlatformIssue,
Other,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetectorDefinition {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<detector_definition::Properties>,
}
pub mod detector_definition {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rank: Option<f64>,
#[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")]
pub is_enabled: Option<bool>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetectorInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(rename = "subCategory", default, skip_serializing_if = "Option::is_none")]
pub sub_category: Option<String>,
#[serde(rename = "supportTopicId", default, skip_serializing_if = "Option::is_none")]
pub support_topic_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetectorResponse {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<detector_response::Properties>,
}
pub mod detector_response {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<DetectorInfo>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dataset: Vec<DiagnosticData>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetectorResponseCollection {
pub value: Vec<DetectorResponse>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticAnalysis {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<diagnostic_analysis::Properties>,
}
pub mod diagnostic_analysis {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "abnormalTimePeriods", default, skip_serializing_if = "Vec::is_empty")]
pub abnormal_time_periods: Vec<AbnormalTimePeriod>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub payload: Vec<AnalysisData>,
#[serde(rename = "nonCorrelatedDetectors", default, skip_serializing_if = "Vec::is_empty")]
pub non_correlated_detectors: Vec<DetectorDefinition>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticAnalysisCollection {
pub value: Vec<AnalysisDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticCategory {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<diagnostic_category::Properties>,
}
pub mod diagnostic_category {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticCategoryCollection {
pub value: Vec<DiagnosticCategory>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticData {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub table: Option<DataTableResponseObject>,
#[serde(rename = "renderingProperties", default, skip_serializing_if = "Option::is_none")]
pub rendering_properties: Option<Rendering>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticDetectorCollection {
pub value: Vec<DetectorDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticDetectorResponse {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<diagnostic_detector_response::Properties>,
}
pub mod diagnostic_detector_response {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "issueDetected", default, skip_serializing_if = "Option::is_none")]
pub issue_detected: Option<bool>,
#[serde(rename = "detectorDefinition", default, skip_serializing_if = "Option::is_none")]
pub detector_definition: Option<DetectorDefinition>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metrics: Vec<DiagnosticMetricSet>,
#[serde(rename = "abnormalTimePeriods", default, skip_serializing_if = "Vec::is_empty")]
pub abnormal_time_periods: Vec<DetectorAbnormalTimePeriod>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub data: Vec<Vec<NameValuePair>>,
#[serde(rename = "responseMetaData", default, skip_serializing_if = "Option::is_none")]
pub response_meta_data: Option<ResponseMetaData>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticMetricSample {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(rename = "roleInstance", default, skip_serializing_if = "Option::is_none")]
pub role_instance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<f64>,
#[serde(rename = "isAggregated", default, skip_serializing_if = "Option::is_none")]
pub is_aggregated: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticMetricSet {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")]
pub time_grain: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<DiagnosticMetricSample>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rendering {
#[serde(rename = "renderingType", default, skip_serializing_if = "Option::is_none")]
pub rendering_type: Option<rendering::RenderingType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
pub mod rendering {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RenderingType {
NoGraph,
Table,
TimeSeries,
TimeSeriesPerInstance,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResponseMetaData {
#[serde(rename = "dataSource", default, skip_serializing_if = "Option::is_none")]
pub data_source: Option<DataSource>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Solution {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<f64>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<solution::Type>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub data: Vec<Vec<NameValuePair>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metadata: Vec<Vec<NameValuePair>>,
}
pub mod solution {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
QuickSolution,
DeepInvestigation,
BestPractices,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationStack {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dependency: Option<String>,
#[serde(rename = "majorVersions", default, skip_serializing_if = "Vec::is_empty")]
pub major_versions: Vec<StackMajorVersion>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub frameworks: Vec<ApplicationStack>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationStackCollection {
pub value: Vec<ApplicationStack>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StackMajorVersion {
#[serde(rename = "displayVersion", default, skip_serializing_if = "Option::is_none")]
pub display_version: Option<String>,
#[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")]
pub runtime_version: Option<String>,
#[serde(rename = "isDefault", default, skip_serializing_if = "Option::is_none")]
pub is_default: Option<bool>,
#[serde(rename = "minorVersions", default, skip_serializing_if = "Vec::is_empty")]
pub minor_versions: Vec<StackMinorVersion>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StackMinorVersion {
#[serde(rename = "displayVersion", default, skip_serializing_if = "Option::is_none")]
pub display_version: Option<String>,
#[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")]
pub runtime_version: Option<String>,
#[serde(rename = "isDefault", default, skip_serializing_if = "Option::is_none")]
pub is_default: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Recommendation {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<recommendation::Properties>,
}
pub mod recommendation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "recommendationId", default, skip_serializing_if = "Option::is_none")]
pub recommendation_id: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "resourceScope", default, skip_serializing_if = "Option::is_none")]
pub resource_scope: Option<properties::ResourceScope>,
#[serde(rename = "ruleName", default, skip_serializing_if = "Option::is_none")]
pub rule_name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<properties::Level>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channels: Option<properties::Channels>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(rename = "actionName", default, skip_serializing_if = "Option::is_none")]
pub action_name: Option<String>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(rename = "nextNotificationTime", default, skip_serializing_if = "Option::is_none")]
pub next_notification_time: Option<String>,
#[serde(rename = "notificationExpirationTime", default, skip_serializing_if = "Option::is_none")]
pub notification_expiration_time: Option<String>,
#[serde(rename = "notifiedTime", default, skip_serializing_if = "Option::is_none")]
pub notified_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<f64>,
#[serde(rename = "isDynamic", default, skip_serializing_if = "Option::is_none")]
pub is_dynamic: Option<bool>,
#[serde(rename = "extensionName", default, skip_serializing_if = "Option::is_none")]
pub extension_name: Option<String>,
#[serde(rename = "bladeName", default, skip_serializing_if = "Option::is_none")]
pub blade_name: Option<String>,
#[serde(rename = "forwardLink", default, skip_serializing_if = "Option::is_none")]
pub forward_link: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResourceScope {
ServerFarm,
Subscription,
WebSite,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Level {
Critical,
Warning,
Information,
NonUrgentSuggestion,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Channels {
Notification,
Api,
Email,
Webhook,
All,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecommendationCollection {
pub value: Vec<Recommendation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecommendationRule {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<recommendation_rule::Properties>,
}
pub mod recommendation_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(rename = "recommendationId", default, skip_serializing_if = "Option::is_none")]
pub recommendation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "actionName", default, skip_serializing_if = "Option::is_none")]
pub action_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<properties::Level>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channels: Option<properties::Channels>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(rename = "isDynamic", default, skip_serializing_if = "Option::is_none")]
pub is_dynamic: Option<bool>,
#[serde(rename = "extensionName", default, skip_serializing_if = "Option::is_none")]
pub extension_name: Option<String>,
#[serde(rename = "bladeName", default, skip_serializing_if = "Option::is_none")]
pub blade_name: Option<String>,
#[serde(rename = "forwardLink", default, skip_serializing_if = "Option::is_none")]
pub forward_link: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Level {
Critical,
Warning,
Information,
NonUrgentSuggestion,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Channels {
Notification,
Api,
Email,
Webhook,
All,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceHealthMetadata {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<resource_health_metadata::Properties>,
}
pub mod resource_health_metadata {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(rename = "signalAvailability", default, skip_serializing_if = "Option::is_none")]
pub signal_availability: Option<bool>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceHealthMetadataCollection {
pub value: Vec<ResourceHealthMetadata>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BillingMeter {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<billing_meter::Properties>,
}
pub mod billing_meter {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "meterId", default, skip_serializing_if = "Option::is_none")]
pub meter_id: Option<String>,
#[serde(rename = "billingLocation", default, skip_serializing_if = "Option::is_none")]
pub billing_location: Option<String>,
#[serde(rename = "shortName", default, skip_serializing_if = "Option::is_none")]
pub short_name: Option<String>,
#[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")]
pub friendly_name: Option<String>,
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BillingMeterCollection {
pub value: Vec<BillingMeter>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsmMoveResourceEnvelope {
#[serde(rename = "targetResourceGroup", default, skip_serializing_if = "Option::is_none")]
pub target_resource_group: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeploymentLocations {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<GeoRegion>,
#[serde(rename = "hostingEnvironments", default, skip_serializing_if = "Vec::is_empty")]
pub hosting_environments: Vec<AppServiceEnvironment>,
#[serde(rename = "hostingEnvironmentDeploymentInfos", default, skip_serializing_if = "Vec::is_empty")]
pub hosting_environment_deployment_infos: Vec<HostingEnvironmentDeploymentInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeoRegion {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<geo_region::Properties>,
}
pub mod geo_region {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeoRegionCollection {
pub value: Vec<GeoRegion>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GlobalCsmSkuDescription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<SkuCapacity>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<Capability>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostingEnvironmentDeploymentInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PremierAddOnOffer {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<premier_add_on_offer::Properties>,
}
pub mod premier_add_on_offer {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub product: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vendor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "promoCodeRequired", default, skip_serializing_if = "Option::is_none")]
pub promo_code_required: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quota: Option<i32>,
#[serde(rename = "webHostingPlanRestrictions", default, skip_serializing_if = "Option::is_none")]
pub web_hosting_plan_restrictions: Option<properties::WebHostingPlanRestrictions>,
#[serde(rename = "privacyPolicyUrl", default, skip_serializing_if = "Option::is_none")]
pub privacy_policy_url: Option<String>,
#[serde(rename = "legalTermsUrl", default, skip_serializing_if = "Option::is_none")]
pub legal_terms_url: Option<String>,
#[serde(rename = "marketplacePublisher", default, skip_serializing_if = "Option::is_none")]
pub marketplace_publisher: Option<String>,
#[serde(rename = "marketplaceOffer", default, skip_serializing_if = "Option::is_none")]
pub marketplace_offer: Option<String>,
}
pub mod properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WebHostingPlanRestrictions {
None,
Free,
Shared,
Basic,
Standard,
Premium,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PremierAddOnOfferCollection {
pub value: Vec<PremierAddOnOffer>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceNameAvailability {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<resource_name_availability::Reason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod resource_name_availability {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
Invalid,
AlreadyExists,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceNameAvailabilityRequest {
pub name: String,
#[serde(rename = "type")]
pub type_: resource_name_availability_request::Type,
#[serde(rename = "isFqdn", default, skip_serializing_if = "Option::is_none")]
pub is_fqdn: Option<bool>,
}
pub mod resource_name_availability_request {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
Site,
Slot,
HostingEnvironment,
PublishingUser,
#[serde(rename = "Microsoft.Web/sites")]
MicrosoftWebSites,
#[serde(rename = "Microsoft.Web/sites/slots")]
MicrosoftWebSitesSlots,
#[serde(rename = "Microsoft.Web/hostingEnvironments")]
MicrosoftWebHostingEnvironments,
#[serde(rename = "Microsoft.Web/publishingUsers")]
MicrosoftWebPublishingUsers,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuInfos {
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skus: Vec<GlobalCsmSkuDescription>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControl {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<source_control::Properties>,
}
pub mod source_control {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
#[serde(rename = "tokenSecret", default, skip_serializing_if = "Option::is_none")]
pub token_secret: Option<String>,
#[serde(rename = "refreshToken", default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")]
pub expiration_time: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceControlCollection {
pub value: Vec<SourceControl>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateProperties {
#[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")]
pub server_farm_id: Option<String>,
#[serde(rename = "skuName", default, skip_serializing_if = "Option::is_none")]
pub sku_name: Option<String>,
#[serde(rename = "needLinuxWorkers", default, skip_serializing_if = "Option::is_none")]
pub need_linux_workers: Option<bool>,
#[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")]
pub is_spot: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<i32>,
#[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")]
pub hosting_environment: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateRequest {
pub name: String,
#[serde(rename = "type")]
pub type_: validate_request::Type,
pub location: String,
pub properties: ValidateProperties,
}
pub mod validate_request {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
ServerFarm,
Site,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ValidateResponseError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ValidateResponseError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetParameters {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_parameters::Properties>,
}
pub mod vnet_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "vnetResourceGroup", default, skip_serializing_if = "Option::is_none")]
pub vnet_resource_group: Option<String>,
#[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_name: Option<String>,
#[serde(rename = "vnetSubnetName", default, skip_serializing_if = "Option::is_none")]
pub vnet_subnet_name: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetValidationFailureDetails {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_validation_failure_details::Properties>,
}
pub mod vnet_validation_failure_details {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed: Option<bool>,
#[serde(rename = "failedTests", default, skip_serializing_if = "Vec::is_empty")]
pub failed_tests: Vec<VnetValidationTestFailure>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VnetValidationTestFailure {
#[serde(flatten)]
pub proxy_only_resource: ProxyOnlyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<vnet_validation_test_failure::Properties>,
}
pub mod vnet_validation_test_failure {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Properties {
#[serde(rename = "testName", default, skip_serializing_if = "Option::is_none")]
pub test_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<String>,
}
}
|
use anyhow::anyhow;
use crate::prelude::*;
const MAX_MONSTERS: i32 = 4;
const MAX_ITEMS: i32 = 2;
const SPAWN_ATTEMPTS_TIMEOUT: i32 = 1000;
const RENDER_ORDER_PLAYER: i32 = 0;
const RENDER_ORDER_MONSTER: i32 = -1;
const RENDER_ORDER_ITEM: i32 = -2;
pub fn player(world: &mut World, config: &Config, x: i32, y: i32) -> anyhow::Result<Entity> {
Ok(world.spawn_resource(
Player,
(
Name("Player".into()),
Position { x, y },
config
.player
.to_renderable_with_render_order(RENDER_ORDER_PLAYER),
Viewshed::with_range(8),
CombatStats {
max_hp: 30,
hp: 30,
defense: 2,
power: 5,
},
),
)?)
}
pub fn rng_monster(world: &mut World, config: &Config, x: i32, y: i32) -> anyhow::Result<Entity> {
let dice_roll = world
.resource::<RandomNumberGenerator>()?
.map(|mut rng| rng.roll_dice(1, 2))?;
let entity = match dice_roll {
1 => orc(world, config, x, y),
_ => goblin(world, config, x, y),
};
Ok(entity)
}
fn orc(world: &mut World, config: &Config, x: i32, y: i32) -> Entity {
monster(
world,
x,
y,
config
.orc
.to_renderable_with_render_order(RENDER_ORDER_MONSTER),
"Orc",
)
}
fn goblin(world: &mut World, config: &Config, x: i32, y: i32) -> Entity {
monster(
world,
x,
y,
config
.goblin
.to_renderable_with_render_order(RENDER_ORDER_MONSTER),
"Goblin",
)
}
fn monster<S: Into<String>>(
world: &mut World,
x: i32,
y: i32,
renderable: Renderable,
name: S,
) -> Entity {
world.spawn((
Monster,
Name(name.into()),
Position { x, y },
renderable,
Viewshed::with_range(8),
BlocksTile,
CombatStats {
max_hp: 16,
hp: 16,
defense: 1,
power: 4,
},
))
}
fn get_random_points_in_rect(
rect: &Rect,
rng: &mut RandomNumberGenerator,
max_points: i32,
) -> Vec<(i32, i32)> {
let mut points = Vec::new();
for _ in 0..max_points {
for _ in 0..SPAWN_ATTEMPTS_TIMEOUT {
let x = rect.x1 + rng.roll_dice(1, rect.width());
let y = rect.y1 + rng.roll_dice(1, rect.height());
let point = (x, y);
if !points.contains(&point) {
points.push(point);
break;
}
}
}
points
}
pub fn rng_room_entities(world: &mut World, config: &Config, room: &Rect) -> anyhow::Result<()> {
let monster_spawn_points;
let item_spawn_points;
{
let mut rng = world.query::<&mut RandomNumberGenerator>();
let (_, rng) = rng
.into_iter()
.next()
.ok_or_else(|| anyhow!("Missing RandomNumberGenerator entity"))?;
let num_monsters = rng.roll_dice(1, MAX_MONSTERS + 2) - 3;
let num_items = rng.roll_dice(1, MAX_ITEMS + 2) - 3;
monster_spawn_points = get_random_points_in_rect(&room, rng, num_monsters);
item_spawn_points = get_random_points_in_rect(&room, rng, num_items);
}
for (x, y) in monster_spawn_points {
rng_monster(world, config, x, y)?;
}
for (x, y) in item_spawn_points {
health_potion(world, config, x, y);
}
Ok(())
}
pub fn health_potion(world: &mut World, config: &Config, x: i32, y: i32) -> Entity {
world.spawn((
Position { x, y },
config
.health_potion
.to_renderable_with_render_order(RENDER_ORDER_ITEM),
Name("Health Potion".into()),
Item,
HealingItem { heal_amount: 8 },
))
}
|
use diesel::result::Error;
//use std::env;
use rocket_contrib::json::Json;
use crate::posts;
use crate::posts::Post;
use crate::connection::DbConn;
use rocket::http::Status;
//use rocket::response::status;
#[get("/")]
pub fn all(connection: DbConn) -> Result<Json<Vec<Post>>, Status> {
posts::repository::all(&connection)
.map(|posts| Json(posts))
.map_err(|error| error_status(error))
}
fn error_status(error: Error) -> Status {
match error {
Error::NotFound => Status::NotFound,
_ => Status::InternalServerError
}
}
// #[get("/<id>")]
// pub fn get(id: i32, connection: DbConn) -> Result<Json<Post>, Status> {
// posts::repository::get(id, &connection)
// .map(|post| Json(post))
// .map_err(|error| error_status(error))
// }
//
// #[post("/", format = "application/json", data = "<post>")]
// pub fn post(post: Json<Post>, connection: DbConn) -> Result<status::Created<Json<Post>>, Status> {
// posts::repository::insert(post.into_inner(), &connection)
// .map(|post| post_created(post))
// .map_err(|error| error_status(error))
// }
//
// fn post_created(post: Post) -> status::Created<Json<Post>> {
// status::Created(
// format!("{host}:{port}/posts/{id}", host = host(), port = port(), id = post.id).to_string(),
// Some(Json(post)))
// }
//
// fn host() -> String {
// env::var("ROCKET_ADDRESS").expect("ROCKET_ADDRESS must be set")
// }
//
// fn port() -> String {
// env::var("ROCKET_PORT").expect("ROCKET_PORT must be set")
// }
//
// #[put("/<id>", format = "application/json", data = "<post>")]
// pub fn put(id: i32, post: Json<Post>, connection: DbConn) -> Result<Json<Post>, Status> {
// posts::repository::update(id, post.into_inner(), &connection)
// .map(|post| Json(post))
// .map_err(|error| error_status(error))
// }
//
// #[delete("/<id>")]
// pub fn delete(id: i32, connection: DbConn) -> Result<Status, Status> {
// match posts::repository::get(id, &connection) {
// Ok(_) => posts::repository::delete(id, &connection)
// .map(|_| Status::NoContent)
// .map_err(|error| error_status(error)),
// Err(error) => Err(error_status(error))
// }
// }
|
use std::borrow::Cow;
use std::fs::{self};
use std::io;
use std::path::{Path, PathBuf};
use pahkat_types::{package::Version};
use typed_builder::TypedBuilder;
#[non_exhaustive]
#[derive(Debug, Clone, TypedBuilder)]
pub struct Request<'a> {
pub repo_path: Cow<'a, Path>,
pub id: Cow<'a, str>,
pub channel: Option<Cow<'a, str>>,
pub version: Cow<'a, Version>,
pub target: Cow<'a, pahkat_types::payload::Target>,
pub url: Option<Cow<'a, url::Url>>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, TypedBuilder)]
pub struct PartialRequest<'a> {
#[builder(default)]
pub repo_path: Option<&'a Path>,
#[builder(default)]
pub id: Option<&'a str>,
#[builder(default)]
pub platform: Option<&'a str>,
#[builder(default)]
pub arch: Option<&'a str>,
#[builder(default)]
pub channel: Option<&'a str>,
#[builder(default)]
pub version: Option<&'a Version>,
#[builder(default)]
pub payload_path: Option<&'a Path>,
#[builder(default)]
pub url: Option<&'a url::Url>,
}
#[derive(Debug, thiserror::Error)]
pub enum RequestError {
#[error("Provided path was invalid")]
PathError(#[source] io::Error),
#[error("Could not find repository at provided path")]
NoRepo(#[from] FindRepoError),
#[error("Could not read payload TOML file")]
Io(#[from] std::io::Error),
#[error("Could not read payload TOML file")]
PayloadToml(#[from] toml::de::Error),
#[error("Invalid input")]
InvalidInput,
}
#[derive(Debug, thiserror::Error)]
pub enum FindRepoError {
#[error("IO error")]
Io(#[from] io::Error),
#[error("No repository found for given path")]
NotFound,
}
fn open_repo(path: &Path) -> Option<pahkat_types::repo::Repository> {
let file = fs::read_to_string(path.join("index.toml")).ok()?;
let repo: pahkat_types::repo::Repository = toml::from_str(&file).ok()?;
Some(repo)
}
fn find_repo(path: &Path) -> Result<&Path, FindRepoError> {
let mut path = path;
if path.ends_with("index.toml") {
path = path.parent().unwrap();
}
if let Some(_) = open_repo(path) {
return Ok(path);
}
while let Some(parent) = path.parent() {
path = parent;
if let Some(_) = open_repo(path) {
return Ok(path);
}
}
Err(FindRepoError::NotFound)
}
impl<'a> crate::Request for Request<'a> {
type Error = RequestError;
type Partial = PartialRequest<'a>;
fn new_from_user_input(partial: Self::Partial) -> Result<Self, Self::Error> {
use dialoguer::Input;
let repo_path = match partial.repo_path {
Some(path) => Cow::Borrowed(path),
None => Input::<String>::new()
.default(
std::env::current_dir()
.ok()
.and_then(|x| x.to_str().map(str::to_string))
.unwrap_or_else(|| ".".into()),
)
.with_prompt("Repository Path")
.interact()
.map(|p| Cow::Owned(PathBuf::from(p)))
.map_err(RequestError::PathError)?,
};
let _ = find_repo(&repo_path)?;
let id = match partial.id {
Some(id) => Cow::Borrowed(id),
None => Cow::Owned(
Input::<String>::new()
.with_prompt("Package identifier")
.interact()
.map_err(|_| RequestError::InvalidInput)?,
),
};
let payload_path = match partial.payload_path {
Some(path) => Cow::Borrowed(path),
None => Cow::Owned(
Input::<String>::new()
.with_prompt("Target path (toml)")
.interact()
.map_err(|_| RequestError::InvalidInput)
.map(std::path::PathBuf::from)?,
),
};
let payload = std::fs::read_to_string(payload_path)?;
let target: pahkat_types::payload::Target = toml::from_str(&payload)?;
let channel = match partial.channel {
Some(channel) => {
if channel == "" {
None
} else {
Some(Cow::Borrowed(channel))
}
}
None => Input::<String>::new()
.with_prompt("Channel (or none for stable)")
.allow_empty(true)
.interact()
.map_err(|_| RequestError::InvalidInput)
.map(|v| if v == "" { None } else { Some(Cow::Owned(v)) })?,
};
let version = match partial.version {
Some(tags) => Cow::Borrowed(tags),
None => Cow::Owned(
Input::<Version>::new()
.with_prompt("Release version")
.interact()
.map_err(|_| RequestError::InvalidInput)?,
),
};
Ok(Request {
repo_path,
id,
channel,
version,
target: Cow::Owned(target),
url: partial.url.map(|x| Cow::Borrowed(x)),
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Failed to read descriptor index: `{0}`")]
ReadFailed(PathBuf, #[source] io::Error),
#[error("Failed to read TOML file `{0}`")]
ReadToml(PathBuf, #[source] toml::de::Error),
#[error("Failed to create directory `{0}`")]
DirCreateFailed(PathBuf, #[source] io::Error),
#[error("Failed to write TOML file `{0}`")]
WriteToml(PathBuf, #[source] io::Error),
#[error("Failed to serialize TOML for `{0}`")]
SerializeToml(PathBuf, #[source] toml::ser::Error),
#[error("Could not find repository at provided path")]
NoRepo(#[from] FindRepoError),
}
pub fn update<'a>(request: Request<'a>) -> Result<(), Error> {
use std::ops::Deref;
log::debug!("{:?}", request);
let pkg_dir = find_repo(&request.repo_path)?
.join("packages")
.join(&*request.id);
let pkg_path = pkg_dir.join("index.toml");
log::debug!("Loading {}", pkg_path.display());
let pkg_file =
std::fs::read_to_string(&pkg_path).map_err(|e| Error::ReadFailed(pkg_path.clone(), e))?;
let mut descriptor: pahkat_types::package::Descriptor =
toml::from_str(&pkg_file).map_err(|e| Error::ReadToml(pkg_path.clone(), e))?;
log::debug!("Loaded {}", pkg_path.display());
let channel = request.channel.as_ref().map(|x| x.deref().to_string());
// Check if a release exists that meets this criteria
let release = match descriptor
.release
.iter_mut()
.find(|x| &x.version == &*request.version && x.channel == channel)
{
Some(release) => {
log::info!("Found release!");
release
}
None => {
log::info!("No release; creating.");
// Insert new releases at front
descriptor.release.insert(
0,
pahkat_types::package::Release::builder()
.channel(channel)
.version(request.version.deref().clone())
.build(),
);
descriptor.release.first_mut().unwrap()
}
};
// Check if a target exists that meets this criteria
let target = match release
.target
.iter_mut()
.find(|x| x.platform == request.target.platform)
{
Some(target) => {
log::info!("Found target!");
*target = (*request.target).to_owned();
target
}
None => {
log::info!("No target; creating.");
release.target.insert(
0,
pahkat_types::payload::Target::builder()
.dependencies(request.target.dependencies.clone())
.platform(request.target.platform.to_string())
.payload(request.target.payload.clone())
.build(),
);
release.target.first_mut().unwrap()
}
};
if let Some(url) = request.url {
log::info!("Setting URL to {}", &url);
target.payload.set_url(url.into_owned());
}
// Write the toml
let data = toml::to_string_pretty(&descriptor)
.map_err(|e| Error::SerializeToml(pkg_path.clone(), e))?;
fs::write(&pkg_path, data).map_err(|e| Error::WriteToml(pkg_path.to_path_buf(), e))?;
log::info!("Wrote descriptor to {}", pkg_path.display());
Ok(())
}
|
#[derive(Default)]
pub struct Metrics {
pub width: f64,
pub height: f64,
}
pub const WINDOW_WIDTH: f64 = 1500.0;
pub const WINDOW_HEIGHT: f64 = 900.0;
|
use crate::{
i8080::error::EmulateError,
i8080::{concat_bytes, Register, Result, I8080},
instruction::{InstructionData, Opcode},
mmu::Mmu,
};
impl I8080 {
/// #LXI - Load Register Pair Immediate
///
/// Opcodes: 0x01, 0x11, 0x21, 0x31
/// Supported Registers: B(0x01), D(0x11), H(0x21), SP(0x31)
/// Params: Two Bytes following opcode
///
/// Loads the 2 bytes following the opcode into the register
/// pair determined from the opcode.
///
/// Returns Ok(()) on success.
///
/// #Errors
/// Fails if given registers A, C, E, L, or M.
pub(crate) fn lxi(&mut self, register: Register, data: InstructionData) -> Result<()> {
if let (Some(high), Some(low)) = data.tuple() {
if let Some(r2) = register.get_pair() {
self.set_8bit_register(register, high);
self.set_8bit_register(r2, low);
} else if register == Register::SP {
self.set_sp(concat_bytes(high, low));
} else {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::LXI(register),
register,
});
}
} else {
return Err(EmulateError::InvalidInstructionData {
opcode: Opcode::LXI(register),
data,
});
}
Ok(())
}
/// #LDA - Load Accumulator from Memory
///
/// Opcodes: 0x3a,
/// Params: Two byte memory location following the opcode
///
/// Loads the byte at the memory location given into the accumulator.
// TODO: WRITE TEST
pub(crate) fn lda<T: Mmu>(&mut self, data: InstructionData, interconnect: &T) -> Result<()> {
if let Some(addr) = data.addr() {
self.set_8bit_register(Register::A, interconnect.read_byte(addr));
} else {
return Err(EmulateError::InvalidInstructionData {
opcode: Opcode::LDA,
data,
});
}
Ok(())
}
/// #STA - Store Accumulator in Memory
///
/// Opcodes: 0x32
/// Params: Two byte memory location following the opcode
///
/// Stores the value in the accumulator into memory at the given address.
// TODO: WRITE TEST
pub(crate) fn sta<T: Mmu>(
&mut self,
data: InstructionData,
interconnect: &mut T,
) -> Result<()> {
if let Some(addr) = data.addr() {
interconnect.write_byte(addr, self.a);
} else {
return Err(EmulateError::InvalidInstructionData {
opcode: Opcode::STA,
data,
});
}
Ok(())
}
/// #LDAX - Load Accumulator
///
/// Opcodes: 0x0a, 0x1a
/// Supported Registers: B(0x0a), D(0x1a)
///
/// The contents of the memory location addressed by registers BC or DE, replace the contents
/// of the accumulator.
///
/// #Errors
/// Fails if given registers A, C, E, H, L, M, SP.
pub(crate) fn ldax<T: Mmu>(&mut self, register: Register, interconnect: &T) -> Result<()> {
let pair = match register {
Register::B | Register::D => register.get_pair().unwrap(),
_r => {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::LDAX(register),
register,
})
}
};
let loc = concat_bytes(
self.get_8bit_register(register)?,
self.get_8bit_register(pair)?,
);
let value = interconnect.read_byte(loc);
self.set_8bit_register(Register::A, value);
Ok(())
}
/// #MOV - Move
///
/// Opcodes: 0x40 - 0x7f; excluding 0x76
/// Supported Registers: A, B, C, D, E, H, L, M
///
/// One byte of data is moved from the register specified
/// by src (the source register) to the register specified
/// by dst (the destination register). The data replaces
/// the contents of the destination register; the source remains unchanged.
///
/// NOTE: MOV using the M register moves data out-of or into memory at location (HL).
///
/// #Errors
/// Fails if given register SP.
pub(crate) fn mov<T: Mmu>(
&mut self,
destination: Register,
source: Register,
interconnect: &mut T,
) -> Result<()> {
match (destination, source) {
(Register::SP, _) | (_, Register::SP) => {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::MOV(destination, source),
register: Register::SP,
})
}
(Register::M, _r) => {
let addr = self.m();
if _r == Register::M {
return Ok(());
};
interconnect.write_byte(addr, self.get_8bit_register(_r)?);
}
(_r, Register::M) => {
let addr = self.m();
self.set_8bit_register(_r, interconnect.read_byte(addr));
}
(_r1, _r2) => self.set_8bit_register(_r1, self.get_8bit_register(_r2)?),
}
Ok(())
}
/// #MVI - Move Immediate Data
///
/// Opcodes: 0x06, 0x0e, 0x16, 0x1e, 0x26, 0x2e, 0x36, 0x3e
/// Supported Registers: A(0x3e), B(0x06), C(0x0e), D(0x16),
/// E(0x1e), H(0x26), L(0x2e), M(0x36)
///
/// The byte of immediate data is stored in the specified register or memory byte.
///
/// #Errors
/// Fails if given register SP.
pub(crate) fn mvi<T: Mmu>(
&mut self,
register: Register,
data: InstructionData,
interconnect: &mut T,
) -> Result<()> {
if let (Some(value), None) = data.tuple() {
match register {
Register::SP => {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::MVI(register),
register,
})
}
Register::M => {
interconnect.write_byte(self.m(), value);
}
_r => {
self.set_8bit_register(register, value);
}
}
} else {
return Err(EmulateError::InvalidInstructionData {
opcode: Opcode::MVI(register),
data,
});
}
Ok(())
}
///PUSH - Push Data Onto Stack
///
/// Opcodes: 0xc5, 0xd5, 0xe5, 0xf5
/// Supported Registers: B(0xc5), D(0xd5), H(0xe5), SP(0xf5)
/// NOTE: We use Register::A to indicate PSW
///
/// The contest of the specified register pair are saved in
/// two bytes of memory indicated by the stack pointer SP.
///
/// The contents of the first register are saved at memory
/// address one less than the address indicated by the stack pointer.
/// If register A(PSW) is specified the first bye of information saved holds the contents of the A
/// register; the second byte holds the settings of the five condition flags (Carry, Zero,
/// Sign, Parity, and Aux Carry.
///
/// #Errors
/// Fails if given registers A, C, E, L, or M
pub(crate) fn push<T: Mmu>(&mut self, register: Register, interconnect: &mut T) -> Result<()> {
match (register, register.get_pair()) {
(_r, Some(r2)) => {
let value = concat_bytes(self.get_8bit_register(_r)?, self.get_8bit_register(r2)?);
self.push_u16(value, interconnect)?;
}
(Register::A, None) => {
let value =
concat_bytes(self.get_8bit_register(Register::A)?, u8::from(self.flags));
self.push_u16(value, interconnect)?;
}
(_r, _) => {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::PUSH(register),
register,
})
}
};
Ok(())
}
/// Pop - Pop Data Off Stack
///
/// Opcodes: 0xc1, 0xd1, 0xe1, 0xf1
/// Supported Registers: B(0xc1), D(0xd1), H(0xe1), SP(0xf1)
/// NOTE: We use Register::A to indicate PSW
///
/// The contents of the specified register pair are restored from two bytes of memory indicated
/// by the Stack Pointer, SP. The byte of memory indicated by the stack pointer is loaded into
/// the second register of the register pair. The byte of of memory at the address one greater
/// than the stack pointer is loaded into the first register of the register pair, unless PSW
/// is indicated, then it is loaded into the conditional flags.
///
/// The Stack Pointer is incremented by 2.
pub(crate) fn pop<T: Mmu>(&mut self, register: Register, interconnect: &T) -> Result<()> {
use crate::i8080::flags::ConditionalFlags;
match (register, register.get_pair()) {
(_r, Some(r2)) => {
let low = self.pop_u8(interconnect)?;
let high = self.pop_u8(interconnect)?;
self.set_8bit_register(_r, high);
self.set_8bit_register(r2, low);
}
(Register::A, None) => {
let flags = self.pop_u8(interconnect)?;
let a = self.pop_u8(interconnect)?;
self.flags = ConditionalFlags::from(flags);
self.set_8bit_register(Register::A, a);
}
(_r, _) => {
return Err(EmulateError::UnsupportedRegister {
opcode: Opcode::POP(register),
register,
})
}
}
Ok(())
}
///XCHG - Exchange Registers
///
/// Opcodes: 0xeb
/// Unary Opcode, No register
///
/// The 16 bits of data held in the H and L registers are exchanged with the 16 bits of data
/// held in the D and E registers.
///
/// Condition flags affected: None,
pub(crate) fn xchg(&mut self) -> Result<()> {
let l = self.l;
let h = self.h;
self.set_8bit_register(Register::L, self.e);
self.set_8bit_register(Register::H, self.d);
self.set_8bit_register(Register::D, h);
self.set_8bit_register(Register::E, l);
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::mmu::Mmu;
use crate::Emulator;
#[test]
fn lxi() {
let bytecode = [
0x01, 0xcc, 0xbb, //LXI B, 0xbbcc
0x11, 0xee, 0xdd, //LXI D, 0xddee
0x21, 0x11, 0xff, //LXI H, 0xff11
0x31, 0xbb, 0xaa, //LXI SP, 0xaabb
];
let mut system = Emulator::new(&bytecode);
system.run();
assert_eq!(system.cpu.b, 0xbb);
assert_eq!(system.cpu.c, 0xcc);
assert_eq!(system.cpu.d, 0xdd);
assert_eq!(system.cpu.e, 0xee);
assert_eq!(system.cpu.h, 0xff);
assert_eq!(system.cpu.l, 0x11);
assert_eq!(system.cpu.sp, 0xaabb);
}
#[test]
fn ldax() {
let bytecode = [
0x0a, // LDAX B
0x1a, // LDAX D
];
let mut system = Emulator::new(&bytecode);
system.cpu.b = 0x20;
system.cpu.d = 0x20;
system.cpu.e = 0x01;
system.mmu_mut().write_byte(0x2000, 0xaa);
system.mmu_mut().write_byte(0x2001, 0xbb);
system.step();
assert_eq!(system.cpu.a, 0xaa);
system.step();
assert_eq!(system.cpu.a, 0xbb);
}
#[test]
fn mov() {
let bytecode = [
0x42, // MOV(B,D)
0x4e, // MOV(C,M)
0x77, // MOV(M,A)
];
let mut system = Emulator::new(&bytecode);
system.cpu.d = 0xbd;
system.cpu.a = 0xaa;
system.cpu.h = 0x20;
system.mmu_mut().write_byte(0x2000, 0xcc);
system.step();
assert_eq!(system.cpu.b, 0xbd);
system.step();
assert_eq!(system.cpu.c, 0xcc);
system.step();
assert_eq!(system.mmu().read_byte(0x2000), 0xaa);
}
#[test]
fn mvi() {
let bytecode = [
0x26, 0x20, //MVI H, 0x20
0x36, 0xff, //MVI M, 0xff
];
let mut system = Emulator::new(&bytecode);
system.run();
assert_eq!(system.cpu.h, 0x20);
assert_eq!(system.mmu().read_byte(0x2000), 0xff);
}
#[test]
fn push() {
let bytecode = [
0xd5, // PUSH D
0xf5, // PUSH PSW
];
let mut system = Emulator::new(&bytecode);
system.cpu.sp = 0x2400;
system.cpu.d = 0x8f;
system.cpu.e = 0x9d;
system.cpu.a = 0x1f;
system.cpu.flags.cy = true;
system.cpu.flags.z = true;
system.cpu.flags.p = true;
system.run();
assert_eq!(system.mmu().read_byte(0x2400 - 1), 0x8f);
assert_eq!(system.mmu().read_byte(0x2400 - 2), 0x9d);
assert_eq!(system.mmu().read_byte(0x2400 - 3), 0x1f);
assert_eq!(system.mmu().read_byte(0x2400 - 4), 0x47);
assert_eq!(system.cpu.sp, 0x2400 - 4);
}
#[test]
fn pop() {
use crate::i8080::ConditionalFlags;
let bytecode = [
0xf5, // PUSH PSW
0xc5, // PUSH B
0xd1, // POP D
0xf1, // POP PSW
];
let mut system = Emulator::new(&bytecode);
system.cpu.sp = 0x2400;
system.cpu.a = 0xaa;
system.cpu.b = 0xbb;
system.cpu.flags.cy = true;
system.cpu.flags.p = true;
system.step();
system.step();
system.cpu.flags = ConditionalFlags::new();
system.step();
assert_eq!(system.cpu.d, 0xbb);
system.step();
assert_eq!(
system.cpu.flags,
ConditionalFlags {
z: false,
s: false,
ac: false,
p: true,
cy: true
}
);
assert_eq!(system.cpu.sp, 0x2400);
}
#[test]
fn xchg() {
let bytecode = [0xeb];
let mut system = Emulator::new(&bytecode);
system.cpu.h = 0x00;
system.cpu.l = 0xff;
system.cpu.d = 0x33;
system.cpu.e = 0x55;
system.run();
assert_eq!(system.cpu.h, 0x33);
assert_eq!(system.cpu.l, 0x55);
assert_eq!(system.cpu.d, 0x00);
assert_eq!(system.cpu.e, 0xff);
}
}
|
#[doc = "Register `DAC_MCR` reader"]
pub type R = crate::R<DAC_MCR_SPEC>;
#[doc = "Register `DAC_MCR` writer"]
pub type W = crate::W<DAC_MCR_SPEC>;
#[doc = "Field `MODE1` reader - DAC Channel 1 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN1=0 and bit CEN1 =0 in the DAC_CR register). If EN1=1 or CEN1 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 1 mode: DAC Channel 1 in normal Mode DAC Channel 1 in sample &amp; hold mode"]
pub type MODE1_R = crate::FieldReader;
#[doc = "Field `MODE1` writer - DAC Channel 1 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN1=0 and bit CEN1 =0 in the DAC_CR register). If EN1=1 or CEN1 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 1 mode: DAC Channel 1 in normal Mode DAC Channel 1 in sample &amp; hold mode"]
pub type MODE1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `DMADOUBLE1` reader - DAC Channel1 DMA double data mode"]
pub type DMADOUBLE1_R = crate::BitReader;
#[doc = "Field `DMADOUBLE1` writer - DAC Channel1 DMA double data mode"]
pub type DMADOUBLE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SINFORMAT1` reader - Enable signed format for DAC channel1"]
pub type SINFORMAT1_R = crate::BitReader;
#[doc = "Field `SINFORMAT1` writer - Enable signed format for DAC channel1"]
pub type SINFORMAT1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HFSEL` reader - High frequency interface mode selection"]
pub type HFSEL_R = crate::FieldReader;
#[doc = "Field `HFSEL` writer - High frequency interface mode selection"]
pub type HFSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `MODE2` reader - DAC Channel 2 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN2=0 and bit CEN2 =0 in the DAC_CR register). If EN2=1 or CEN2 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 2 mode: DAC Channel 2 in normal Mode DAC Channel 2 in sample &amp; hold mode"]
pub type MODE2_R = crate::FieldReader;
#[doc = "Field `MODE2` writer - DAC Channel 2 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN2=0 and bit CEN2 =0 in the DAC_CR register). If EN2=1 or CEN2 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 2 mode: DAC Channel 2 in normal Mode DAC Channel 2 in sample &amp; hold mode"]
pub type MODE2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `DMADOUBLE2` reader - DAC Channel2 DMA double data mode"]
pub type DMADOUBLE2_R = crate::BitReader;
#[doc = "Field `DMADOUBLE2` writer - DAC Channel2 DMA double data mode"]
pub type DMADOUBLE2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SINFORMAT2` reader - Enable signed format for DAC channel2"]
pub type SINFORMAT2_R = crate::BitReader;
#[doc = "Field `SINFORMAT2` writer - Enable signed format for DAC channel2"]
pub type SINFORMAT2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:2 - DAC Channel 1 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN1=0 and bit CEN1 =0 in the DAC_CR register). If EN1=1 or CEN1 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 1 mode: DAC Channel 1 in normal Mode DAC Channel 1 in sample &amp; hold mode"]
#[inline(always)]
pub fn mode1(&self) -> MODE1_R {
MODE1_R::new((self.bits & 7) as u8)
}
#[doc = "Bit 8 - DAC Channel1 DMA double data mode"]
#[inline(always)]
pub fn dmadouble1(&self) -> DMADOUBLE1_R {
DMADOUBLE1_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Enable signed format for DAC channel1"]
#[inline(always)]
pub fn sinformat1(&self) -> SINFORMAT1_R {
SINFORMAT1_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bits 14:15 - High frequency interface mode selection"]
#[inline(always)]
pub fn hfsel(&self) -> HFSEL_R {
HFSEL_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bits 16:18 - DAC Channel 2 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN2=0 and bit CEN2 =0 in the DAC_CR register). If EN2=1 or CEN2 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 2 mode: DAC Channel 2 in normal Mode DAC Channel 2 in sample &amp; hold mode"]
#[inline(always)]
pub fn mode2(&self) -> MODE2_R {
MODE2_R::new(((self.bits >> 16) & 7) as u8)
}
#[doc = "Bit 24 - DAC Channel2 DMA double data mode"]
#[inline(always)]
pub fn dmadouble2(&self) -> DMADOUBLE2_R {
DMADOUBLE2_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Enable signed format for DAC channel2"]
#[inline(always)]
pub fn sinformat2(&self) -> SINFORMAT2_R {
SINFORMAT2_R::new(((self.bits >> 25) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - DAC Channel 1 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN1=0 and bit CEN1 =0 in the DAC_CR register). If EN1=1 or CEN1 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 1 mode: DAC Channel 1 in normal Mode DAC Channel 1 in sample &amp; hold mode"]
#[inline(always)]
#[must_use]
pub fn mode1(&mut self) -> MODE1_W<DAC_MCR_SPEC, 0> {
MODE1_W::new(self)
}
#[doc = "Bit 8 - DAC Channel1 DMA double data mode"]
#[inline(always)]
#[must_use]
pub fn dmadouble1(&mut self) -> DMADOUBLE1_W<DAC_MCR_SPEC, 8> {
DMADOUBLE1_W::new(self)
}
#[doc = "Bit 9 - Enable signed format for DAC channel1"]
#[inline(always)]
#[must_use]
pub fn sinformat1(&mut self) -> SINFORMAT1_W<DAC_MCR_SPEC, 9> {
SINFORMAT1_W::new(self)
}
#[doc = "Bits 14:15 - High frequency interface mode selection"]
#[inline(always)]
#[must_use]
pub fn hfsel(&mut self) -> HFSEL_W<DAC_MCR_SPEC, 14> {
HFSEL_W::new(self)
}
#[doc = "Bits 16:18 - DAC Channel 2 mode These bits can be written only when the DAC is disabled and not in the calibration mode (when bit EN2=0 and bit CEN2 =0 in the DAC_CR register). If EN2=1 or CEN2 =1 the write operation is ignored. They can be set and cleared by software to select the DAC Channel 2 mode: DAC Channel 2 in normal Mode DAC Channel 2 in sample &amp; hold mode"]
#[inline(always)]
#[must_use]
pub fn mode2(&mut self) -> MODE2_W<DAC_MCR_SPEC, 16> {
MODE2_W::new(self)
}
#[doc = "Bit 24 - DAC Channel2 DMA double data mode"]
#[inline(always)]
#[must_use]
pub fn dmadouble2(&mut self) -> DMADOUBLE2_W<DAC_MCR_SPEC, 24> {
DMADOUBLE2_W::new(self)
}
#[doc = "Bit 25 - Enable signed format for DAC channel2"]
#[inline(always)]
#[must_use]
pub fn sinformat2(&mut self) -> SINFORMAT2_W<DAC_MCR_SPEC, 25> {
SINFORMAT2_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "DAC mode control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dac_mcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dac_mcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DAC_MCR_SPEC;
impl crate::RegisterSpec for DAC_MCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dac_mcr::R`](R) reader structure"]
impl crate::Readable for DAC_MCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dac_mcr::W`](W) writer structure"]
impl crate::Writable for DAC_MCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DAC_MCR to value 0"]
impl crate::Resettable for DAC_MCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::fs;
extern crate yaml_rust;
use yaml_rust::{YamlLoader};
fn main() {
let contents = fs::read_to_string("config.yaml").expect("Something went wrong reading the file");
let docs = YamlLoader::load_from_str(&contents).unwrap();
let doc = &docs[0];
println!("{:#?}", doc);
let packages = &doc["packages"];
let apt = &packages["apt"];
let dnf = &packages["dnf"];
let directories = &doc["directories"];
println!("{:#?}", apt);
println!("{:#?}", dnf);
println!("{:#?}", directories);
} |
use std::collections::HashSet;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum Cell {
Empty,
Cross,
Naught,
}
impl Default for Cell {
fn default() -> Self {
Self::Empty
}
}
#[derive(Debug, Default)]
struct Board([Cell; 9]);
impl Board {
fn is_complete(&self) -> bool {
// There aren't many winning (or drawing) combinations, so we'll just brute force this.
if match self.0 {
[a, b, c, _, _, _, _, _, _] if a == b && a == c && a != Cell::Empty => true,
[_, _, _, a, b, c, _, _, _] if a == b && a == c && a != Cell::Empty => true,
[_, _, _, _, _, _, a, b, c] if a == b && a == c && a != Cell::Empty => true,
[a, _, _, b, _, _, c, _, _] if a == b && a == c && a != Cell::Empty => true,
[_, a, _, _, b, _, _, c, _] if a == b && a == c && a != Cell::Empty => true,
[_, _, a, _, _, b, _, _, c] if a == b && a == c && a != Cell::Empty => true,
[a, _, _, _, b, _, _, _, c] if a == b && a == c && a != Cell::Empty => true,
[_, _, a, _, b, _, c, _, _] if a == b && a == c && a != Cell::Empty => true,
[a, b, c, d, e, f, g, h, i]
if a != Cell::Empty
&& b != Cell::Empty
&& c != Cell::Empty
&& d != Cell::Empty
&& e != Cell::Empty
&& f != Cell::Empty
&& g != Cell::Empty
&& h != Cell::Empty
&& i != Cell::Empty =>
{
true
}
_ => false,
} {
return true;
}
false
}
fn set(&mut self, i: usize, cell: Cell) {
self.0[i] = cell;
}
}
fn main() {
let mut moves = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let mut seen = HashSet::new();
permutohedron::heap_recursive(&mut moves, |p| {
let mut board = Board::default();
for (i, &mut pos) in p.into_iter().enumerate() {
board.set(
pos,
if i % 2 == 0 {
Cell::Cross
} else {
Cell::Naught
},
);
if board.is_complete() {
seen.insert(p[0..i + 1].to_vec());
break;
}
}
()
});
println!("{}", seen.len());
}
|
/// EVM instruction opcodes
pub type Opcode = u8;
pub const STOP: Opcode = 0x00;
pub const ADD: Opcode = 0x01;
pub const MUL: Opcode = 0x02;
pub const SUB: Opcode = 0x03;
pub const DIV: Opcode = 0x04;
pub const SDIV: Opcode = 0x05;
pub const MOD: Opcode = 0x06;
pub const SMOD: Opcode = 0x07;
pub const ADDMOD: Opcode = 0x08;
pub const MULMOD: Opcode = 0x09;
pub const EXP: Opcode = 0x0a;
pub const SIGNEXTEND: Opcode = 0x0b;
pub const LT: Opcode = 0x10;
pub const GT: Opcode = 0x11;
pub const SLT: Opcode = 0x12;
pub const SGT: Opcode = 0x13;
pub const EQ: Opcode = 0x14;
pub const ISZERO: Opcode = 0x15;
pub const AND: Opcode = 0x16;
pub const OR: Opcode = 0x17;
pub const XOR: Opcode = 0x18;
pub const NOT: Opcode = 0x19;
pub const BYTE: Opcode = 0x1a;
pub const SHA3: Opcode = 0x20;
pub const ADDRESS: Opcode = 0x30;
pub const BALANCE: Opcode = 0x31;
pub const ORIGIN: Opcode = 0x32;
pub const CALLER: Opcode = 0x33;
pub const CALLVALUE: Opcode = 0x34;
pub const CALLDATALOAD: Opcode = 0x35;
pub const CALLDATASIZE: Opcode = 0x36;
pub const CALLDATACOPY: Opcode = 0x37;
pub const CODESIZE: Opcode = 0x38;
pub const CODECOPY: Opcode = 0x39;
pub const GASPRICE: Opcode = 0x3a;
pub const EXTCODESIZE: Opcode = 0x3b;
pub const EXTCODECOPY: Opcode = 0x3c;
pub const RETURNDATASIZE: Opcode = 0x3d;
pub const RETURNDATACOPY: Opcode = 0x3e;
pub const BLOCKHASH: Opcode = 0x40;
pub const COINBASE: Opcode = 0x41;
pub const TIMESTAMP: Opcode = 0x42;
pub const NUMBER: Opcode = 0x43;
pub const DIFFICULTY: Opcode = 0x44;
pub const GASLIMIT: Opcode = 0x45;
pub const POP: Opcode = 0x50;
pub const MLOAD: Opcode = 0x51;
pub const MSTORE: Opcode = 0x52;
pub const MSTORE8: Opcode = 0x53;
pub const SLOAD: Opcode = 0x54;
pub const SSTORE: Opcode = 0x55;
pub const JUMP: Opcode = 0x56;
pub const JUMPI: Opcode = 0x57;
pub const PC: Opcode = 0x58;
pub const MSIZE: Opcode = 0x59;
pub const GAS: Opcode = 0x5a;
pub const JUMPDEST: Opcode = 0x5b;
pub const PUSH1: Opcode = 0x60;
pub const PUSH2: Opcode = 0x61;
pub const PUSH3: Opcode = 0x62;
pub const PUSH4: Opcode = 0x63;
pub const PUSH5: Opcode = 0x64;
pub const PUSH6: Opcode = 0x65;
pub const PUSH7: Opcode = 0x66;
pub const PUSH8: Opcode = 0x67;
pub const PUSH9: Opcode = 0x68;
pub const PUSH10: Opcode = 0x69;
pub const PUSH11: Opcode = 0x6a;
pub const PUSH12: Opcode = 0x6b;
pub const PUSH13: Opcode = 0x6c;
pub const PUSH14: Opcode = 0x6d;
pub const PUSH15: Opcode = 0x6e;
pub const PUSH16: Opcode = 0x6f;
pub const PUSH17: Opcode = 0x70;
pub const PUSH18: Opcode = 0x71;
pub const PUSH19: Opcode = 0x72;
pub const PUSH20: Opcode = 0x73;
pub const PUSH21: Opcode = 0x74;
pub const PUSH22: Opcode = 0x75;
pub const PUSH23: Opcode = 0x76;
pub const PUSH24: Opcode = 0x77;
pub const PUSH25: Opcode = 0x78;
pub const PUSH26: Opcode = 0x79;
pub const PUSH27: Opcode = 0x7a;
pub const PUSH28: Opcode = 0x7b;
pub const PUSH29: Opcode = 0x7c;
pub const PUSH30: Opcode = 0x7d;
pub const PUSH31: Opcode = 0x7e;
pub const PUSH32: Opcode = 0x7f;
pub const DUP1: Opcode = 0x80;
pub const DUP2: Opcode = 0x81;
pub const DUP3: Opcode = 0x82;
pub const DUP4: Opcode = 0x83;
pub const DUP5: Opcode = 0x84;
pub const DUP6: Opcode = 0x85;
pub const DUP7: Opcode = 0x86;
pub const DUP8: Opcode = 0x87;
pub const DUP9: Opcode = 0x88;
pub const DUP10: Opcode = 0x89;
pub const DUP11: Opcode = 0x8a;
pub const DUP12: Opcode = 0x8b;
pub const DUP13: Opcode = 0x8c;
pub const DUP14: Opcode = 0x8d;
pub const DUP15: Opcode = 0x8e;
pub const DUP16: Opcode = 0x8f;
pub const SWAP1: Opcode = 0x90;
pub const SWAP2: Opcode = 0x91;
pub const SWAP3: Opcode = 0x92;
pub const SWAP4: Opcode = 0x93;
pub const SWAP5: Opcode = 0x94;
pub const SWAP6: Opcode = 0x95;
pub const SWAP7: Opcode = 0x96;
pub const SWAP8: Opcode = 0x97;
pub const SWAP9: Opcode = 0x98;
pub const SWAP10: Opcode = 0x99;
pub const SWAP11: Opcode = 0x9a;
pub const SWAP12: Opcode = 0x9b;
pub const SWAP13: Opcode = 0x9c;
pub const SWAP14: Opcode = 0x9d;
pub const SWAP15: Opcode = 0x9e;
pub const SWAP16: Opcode = 0x9f;
pub const LOG0: Opcode = 0xa0;
pub const LOG1: Opcode = 0xa1;
pub const LOG2: Opcode = 0xa2;
pub const LOG3: Opcode = 0xa3;
pub const LOG4: Opcode = 0xa4;
pub const CREATE: Opcode = 0xf0;
pub const CALL: Opcode = 0xf1;
pub const CALLCODE: Opcode = 0xf2;
pub const RETURN: Opcode = 0xf3;
pub const DELEGATECALL: Opcode = 0xf4;
pub const STATICCALL: Opcode = 0xfa;
pub const REVERT: Opcode = 0xfd;
pub const INVALID: Opcode = 0xfe;
pub const SELFDESTRUCT: Opcode = 0xff;
|
#[doc = "Reader of register DDRPERFM_ISR"]
pub type R = crate::R<u32, super::DDRPERFM_ISR>;
#[doc = "Reader of field `OVFF`"]
pub type OVFF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - OVFF"]
#[inline(always)]
pub fn ovff(&self) -> OVFF_R {
OVFF_R::new((self.bits & 0x01) != 0)
}
}
|
use crate::{apu, bus, controller as ctrl, cpu, parse, ppu, serialize};
use bus::{CpuAddressBus, CpuAddressBusBase, Mmc3CpuAddressBus, NromCpuAddressBus, PpuAddressBus};
use std::cell::Cell;
// wrapper struct around 'CpuAddressBus' implementations that stores writes
// in the 0x6000 area (blargg's tests output a result string to these addresses)
pub struct TestCpuAddressBus<A> {
bus: A,
// the output string (we assume a max size of 256 chars)
test_output: [u8; 0x100],
// the test status written to 0x6000
test_status: Option<u8>,
}
impl<'a> TestCpuAddressBus<NromCpuAddressBus<'a>> {
pub fn new(
prg_rom: &[u8],
chr_ram: &[u8],
mirroring: parse::MirroringType,
ppu: ppu::Ppu,
apu: apu::Apu,
controller: ctrl::Controller,
framebuffer: &'a [Cell<u32>; 256 * 240],
) -> Self {
Self {
bus: NromCpuAddressBus::new(
prg_rom,
chr_ram,
mirroring,
ppu,
apu,
controller,
framebuffer,
),
test_output: [0; 0x100],
test_status: None,
}
}
}
// // TODO: make the 'new()' method on 'NromAddressBus' and 'Mmc3CpuAddressBus'
// // a part of the 'CpuAddressBus' trait to remove this code duplication
impl<'a> TestCpuAddressBus<Mmc3CpuAddressBus<'a>> {
pub fn new(
prg_rom: &[u8],
chr_ram: &[u8],
mirroring: parse::MirroringType,
ppu: ppu::Ppu,
apu: apu::Apu,
controller: ctrl::Controller,
framebuffer: &'a [Cell<u32>; 256 * 240],
) -> Self {
Self {
bus: Mmc3CpuAddressBus::new(
prg_rom,
chr_ram,
mirroring,
ppu,
apu,
controller,
framebuffer,
),
test_output: [0; 0x100],
test_status: None,
}
}
}
// 'Serialize' is required by the 'CpuAddressBus' trait
impl<'a, A> serialize::Serialize for TestCpuAddressBus<A>
where
A: CpuAddressBus<'a>,
{
fn serialize(&self, file: &mut std::io::BufWriter<std::fs::File>) -> Result<(), String> {
Ok(())
}
fn deserialize(&mut self, file: &mut std::io::BufReader<std::fs::File>) -> Result<(), String> {
Ok(())
}
}
impl<'a, A> CpuAddressBus<'a> for TestCpuAddressBus<A>
where
A: CpuAddressBus<'a>,
{
fn read(&mut self, addr: u16, cpu: &mut cpu::Cpu) -> u8 {
if addr >= 0x6004 && addr <= 0x6004 + self.test_output.len() as u16 {
self.test_output[addr as usize - 0x6004]
} else if addr == 0x6000 {
self.test_status.unwrap_or(0xff)
} else {
self.bus.read(addr, cpu)
}
}
fn write(&mut self, addr: u16, val: u8, cpu: &mut cpu::Cpu) {
if addr >= 0x6004 && addr <= 0x6004 + self.test_output.len() as u16 {
self.test_output[addr as usize - 0x6004] = val;
} else if addr == 0x6000 {
self.test_status = Some(val);
}
self.bus.write(addr, val, cpu);
}
fn base(&mut self) -> (&mut CpuAddressBusBase<'a>, &mut dyn PpuAddressBus) {
self.bus.base()
}
}
#[cfg(test)]
fn run_test(rom_path: &str, expected_test_output: &str) {
let mut rom_file = std::fs::File::open(rom_path).unwrap();
let framebuffer = Cell::new([0u32; 256 * 240]);
let mut nes = crate::Nes::new(
unsafe { &*(&framebuffer as *const _ as *const _) },
&mut rom_file,
);
nes.cpu.pc = u16::from_le_bytes([
nes.bus.read(0xfffc, &mut nes.cpu),
nes.bus.read(0xfffd, &mut nes.cpu),
]);
// run nes until test status at 0x6000 indicates that
// the test results have been written to 0x6004-
while nes.bus.read(0x6000, &mut nes.cpu) >= 0x80 {
while !nes.bus.base().0.ppu.is_frame_done() {
nes.cpu.exec_instruction(nes.bus);
let (base, ppu_bus) = nes.bus.base();
let framebuffer = base.framebuffer;
base.ppu.catch_up(&mut nes.cpu, ppu_bus, framebuffer);
}
// reset counters
let base = nes.bus.base().0;
base.ppu.sub_cycle_count(nes.cpu.cycle_count as i32 * 3);
base.ppu.set_frame_done(false);
nes.cpu.cycle_count = 0;
}
let mut test_output = String::new();
let mut addr = 0x6004;
loop {
let character = nes.bus.read(addr, &mut nes.cpu);
if character == 0 {
break;
} else {
test_output.push(character as char);
addr += 1;
}
}
assert_eq!(test_output, expected_test_output);
}
#[test]
fn instr_test_v5() {
run_test(
"src/test/instr_test-v5/rom_singles/01-basics.nes",
"\n01-basics\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/02-implied.nes",
"\n02-implied\n\nPassed\n",
);
// NOTE: tests 03 through 09 fail due to invalid opcodes
run_test(
"src/test/instr_test-v5/rom_singles/10-branches.nes",
"\n10-branches\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/11-stack.nes",
"\n11-stack\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/12-jmp_jsr.nes",
"\n12-jmp_jsr\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/13-rts.nes",
"\n13-rts\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/14-rti.nes",
"\n14-rti\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/15-brk.nes",
"\n15-brk\n\nPassed\n",
);
run_test(
"src/test/instr_test-v5/rom_singles/16-special.nes",
"\n16-special\n\nPassed\n",
);
}
#[test]
fn instr_misc() {
run_test(
"src/test/instr_misc/rom_singles/01-abs_x_wrap.nes",
"\n01-abs_x_wrap\n\nPassed\n",
);
run_test(
"src/test/instr_misc/rom_singles/02-branch_wrap.nes",
"\n02-branch_wrap\n\nPassed\n",
);
run_test(
"src/test/instr_misc/rom_singles/03-dummy_reads.nes",
"\n03-dummy_reads\n\nPassed\n",
);
// NOTE: '04-dummy_reads_apu' fails since apu emulation isn't implemented yet
}
#[test]
fn instr_timing() {
// NOTE: both '1-instr_timing' and '2-branch_timing' fail due to lack of apu support
}
#[test]
fn cpu_timing_test6() {
// NOTE: this test passes, but i've yet to implement a way of verifiying it in code
// TODO: allow testing roms that don't output results to 0x6000
}
#[test]
fn branch_timing_tests() {
// NOTE: all of these tests pass, but haven't been automated for the same reason as above
}
#[test]
fn ppu_vbl_nmi() {
run_test(
"src/test/ppu_vbl_nmi/rom_singles/01-vbl_basics.nes",
"\n01-vbl_basics\n\nPassed\n",
);
run_test(
"src/test/ppu_vbl_nmi/rom_singles/02-vbl_set_time.nes",
"T+ 1 2\n00 - V\n01 - V\n02 - V\n03 - V\n04 - -\n05 V \
-\n06 V -\n07 V -\n08 V -\n\n02-vbl_set_time\n\nPassed\n",
);
run_test(
"src/test/ppu_vbl_nmi/rom_singles/03-vbl_clear_time.nes",
"00 V\n01 V\n02 V\n03 V\n04 V\n05 V\n06 -\n07 -\n08 -\n\
\n03-vbl_clear_time\n\nPassed\n",
);
run_test(
"src/test/ppu_vbl_nmi/rom_singles/04-nmi_control.nes",
"\n04-nmi_control\n\nPassed\n",
);
// NOTE: '05-nmi-timing' fails due to lack of cycle accurate nmi polling
run_test(
"src/test/ppu_vbl_nmi/rom_singles/06-suppression.nes",
"00 - N\n01 - N\n02 - N\n03 - N\n04 - -\n05 V -\n06 V \
-\n07 V N\n08 V N\n09 V N\n\n06-suppression\n\nPassed\n",
);
// NOTE: '07-nmi_on_timing' fails for unknown reasons (many
// other emulators seem to struggle with this one)
run_test(
"src/test/ppu_vbl_nmi/rom_singles/08-nmi_off_timing.nes",
"03 -\n04 -\n05 -\n06 -\n07 N\n08 N\n09 N\n0A N\n0B N\n0C \
N\n\n08-nmi_off_timing\n\nPassed\n",
);
run_test(
"src/test/ppu_vbl_nmi/rom_singles/09-even_odd_frames.nes",
"00 01 01 02 \n09-even_odd_frames\n\nPassed\n",
);
// NOTE: '10-even_odd_timing' fails due to cycle inaccuracies (the last
// 8 cycles of the pre-render line all have to be run in one step)
}
#[test]
fn ppu_sprite_overflow() {
run_test(
"src/test/ppu_sprite_overflow/rom_singles/01-basics.nes",
"\n01-basics\n\nPassed\n",
);
run_test(
"src/test/ppu_sprite_overflow/rom_singles/02-details.nes",
"\n02-details\n\nPassed\n",
);
// NOTE: test 03 fails (for reasons i've yet to investigate)
run_test(
"src/test/ppu_sprite_overflow/rom_singles/04-obscure.nes",
"\n04-obscure\n\nPassed\n",
);
// NOTE: test 05 also fails
}
#[test]
fn mmc3_test_2() {
run_test(
"src/test/mmc3_test_2/rom_singles/1-clocking.nes",
"\n1-clocking\n\nPassed\n",
);
run_test(
"src/test/mmc3_test_2/rom_singles/2-details.nes",
"\n2-details\n\nPassed\n",
);
run_test(
"src/test/mmc3_test_2/rom_singles/3-A12_clocking.nes",
"\n3-A12_clocking\n\nPassed\n",
);
// NOTE: '4-scanline_timing' fails due to cycle inaccuracies (most likely caused by
// the fact that the 8 cycles at dot 257-265 all have to be executed in one step)
run_test(
"src/test/mmc3_test_2/rom_singles/5-MMC3.nes",
"\n5-MMC3\n\nPassed\n",
);
// NOTE: '6-MMC3_alt' fails since only newer MMC3 revisions are supported
// (both A and B can't be supported at once)
}
|
//! Working with recorded timesheets (lists of events).
use std::{
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
};
use chrono::{DateTime, Duration, Utc};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::Event;
/// List of events, together comprising a log of work from which totals can be calculated for
/// various periods of time.
#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Sheet {
pub events: Vec<Event>,
}
impl Sheet {
/// Attempt to load a sheet from the file at the default location, as determined by
/// [`default_loc()`][default].
///
/// [default]: #method.default_loc
pub fn load_default() -> Result<Sheet, SheetError> {
Self::load(Self::default_loc()?)
}
/// Attempt to load a sheet from the file at the given path.
pub fn load<P>(path: P) -> Result<Sheet, SheetError>
where
P: AsRef<Path>,
{
let mut sheet_json = String::new();
{
let mut sheet_file = File::open(&path).map_err(SheetError::OpenSheet)?;
sheet_file
.read_to_string(&mut sheet_json)
.map_err(SheetError::ReadSheet)?;
}
if sheet_json.is_empty() {
Ok(Sheet::default())
} else {
serde_json::from_str(&sheet_json).map_err(SheetError::ParseSheet)
}
}
/// Get the default directory in which sheets are stored.
///
/// The directory is determined using the [directories][directories] crate by platform as
/// follows:
///
/// + Linux: `$XDG_CONFIG_HOME/punchclock/sheet.json`
/// + macOS: `$HOME/Library/Application Support/dev.neros.PunchClock/sheet.json`
/// + Windows: `%APPDATA%\Local\Neros\PunchClock\sheet.json`
///
/// [directories]: https://crates.io/crates/directories
pub fn default_dir() -> Result<PathBuf, SheetError> {
ProjectDirs::from("dev", "neros", "PunchClock")
.ok_or(SheetError::FindSheet)
.map(|dirs| dirs.data_dir().to_owned())
}
/// Get the path to the file the default sheet is stored in.
///
/// This is the file `sheet.json` inside the directory returned from
/// [`default_dir()`][default].
///
/// [default]: #method.default_dir
pub fn default_loc() -> Result<PathBuf, SheetError> {
Self::default_dir().map(|mut dir| {
dir.push("sheet.json");
dir
})
}
/// Attempt to write a sheet to the file at the default location, as determined by
/// [`default_loc()`][default].
///
/// [default]: #method.default_loc
pub fn write_default(&self) -> Result<(), SheetError> {
self.write(Self::default_loc()?)
}
/// Attempt to write a sheet to the file at the given path.
pub fn write<P>(&self, path: P) -> Result<(), SheetError>
where
P: AsRef<Path>,
{
let new_sheet_json = serde_json::to_string(self).unwrap();
match File::create(&path) {
Ok(mut sheet_file) => {
write!(&mut sheet_file, "{}", new_sheet_json).map_err(SheetError::WriteSheet)
}
Err(e) => Err(SheetError::WriteSheet(e)),
}
}
/// Record a punch-in (start of a time-tracking period) at the current time.
pub fn punch_in(&mut self) -> Result<DateTime<Utc>, SheetError> {
self.punch_in_at(Utc::now())
}
/// Record a punch-in (start of a time-tracking period) at the given time.
pub fn punch_in_at(&mut self, time: DateTime<Utc>) -> Result<DateTime<Utc>, SheetError> {
match self.events.last() {
Some(Event { stop: Some(_), .. }) | None => {
let event = Event::new(time);
self.events.push(event);
Ok(time)
}
Some(Event {
start: start_time, ..
}) => Err(SheetError::PunchedIn(*start_time)),
}
}
/// Record a punch-out (end of a time-tracking period) at the current time.
pub fn punch_out(&mut self) -> Result<DateTime<Utc>, SheetError> {
self.punch_out_at(Utc::now())
}
/// Record a punch-out (end of a time-tracking period) at the given time.
pub fn punch_out_at(&mut self, time: DateTime<Utc>) -> Result<DateTime<Utc>, SheetError> {
match self.events.last_mut() {
Some(ref mut event @ Event { stop: None, .. }) => {
event.stop = Some(time);
Ok(time)
}
Some(Event {
stop: Some(stop_time),
..
}) => Err(SheetError::PunchedOut(*stop_time)),
None => Err(SheetError::NoPunches),
}
}
/// Get the current status of time-tracking, including the time at which the status last
/// changed.
pub fn status(&self) -> SheetStatus {
match self.events.last() {
Some(Event {
stop: Some(stop), ..
}) => SheetStatus::PunchedOut(*stop),
Some(Event { start, .. }) => SheetStatus::PunchedIn(*start),
None => SheetStatus::Empty,
}
}
/// Count the amount of time for which there was recorded work between the two given instants,
/// including an ongoing time-tracking period if there is one.
pub fn count_range(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Duration {
self.events
.iter()
.map(|e| (e.start, e.stop.unwrap_or_else(Utc::now)))
.filter(|(start, stop)| {
let entirely_before = start < &begin && stop < &begin;
let entirely_after = start > &end && stop > &end;
!(entirely_before || entirely_after)
})
.map(|(start, stop)| {
let real_begin = std::cmp::max(begin, start);
let real_end = std::cmp::min(end, stop);
real_end - real_begin
})
.fold(Duration::zero(), |acc, next| acc + next)
}
}
/// Whether or not time is currently being tracked.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SheetStatus {
/// Time is currently being tracked, and has been since the given instant.
PunchedIn(DateTime<Utc>),
/// Time is not currently being tracked, as of the given instant.
PunchedOut(DateTime<Utc>),
/// No time has ever been tracked.
Empty,
}
/// Errors arising through the use of [`Sheet`][sheet].
///
/// [sheet]: ./struct.Sheet.html
#[derive(Error, Debug)]
pub enum SheetError {
#[error("already punched in at {0}")]
PunchedIn(DateTime<Utc>),
#[error("not punched in, last punched out at {0}")]
PunchedOut(DateTime<Utc>),
#[error("not punched in, no punch-ins recorded")]
NoPunches,
#[error("unable to find sheet file")]
FindSheet,
#[error("unable to open sheet file")]
OpenSheet(#[source] std::io::Error),
#[error("unable to read sheet file")]
ReadSheet(#[source] std::io::Error),
#[error("unable to parse sheet")]
ParseSheet(#[source] serde_json::Error),
#[error("unable to write sheet to file")]
WriteSheet(#[source] std::io::Error),
}
|
fn main() {
println!("Try running each binary under /bin...");
let duration = std::time::Duration::from_millis(1000);
print!("\ra");
std::thread::sleep(duration);
print!("\rb");
std::thread::sleep(duration);
print!("\rc");
std::thread::sleep(duration);
print!("\rd");
std::thread::sleep(duration);
print!("\re");
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// TableWidgetCellDisplayMode : Define a display mode for the table cell.
/// Define a display mode for the table cell.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum TableWidgetCellDisplayMode {
#[serde(rename = "number")]
NUMBER,
#[serde(rename = "bar")]
BAR,
}
impl ToString for TableWidgetCellDisplayMode {
fn to_string(&self) -> String {
match self {
Self::NUMBER => String::from("number"),
Self::BAR => String::from("bar"),
}
}
}
|
// Magical Bitcoin Library
// Written in 2020 by
// Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020 Magical Bitcoin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use std::fs;
use std::path::PathBuf;
#[cfg(feature = "rpc")]
use bitcoin::secp256k1::Secp256k1;
use bitcoin::Network;
use clap::AppSettings;
use log::{debug, error, info, warn};
#[cfg(feature = "repl")]
use rustyline::error::ReadlineError;
#[cfg(feature = "repl")]
use rustyline::Editor;
use structopt::StructOpt;
#[cfg(feature = "compact_filters")]
use bdk::blockchain::compact_filters::{BitcoinPeerConfig, CompactFiltersBlockchainConfig};
#[cfg(feature = "electrum")]
use bdk::blockchain::electrum::ElectrumBlockchainConfig;
#[cfg(feature = "esplora")]
use bdk::blockchain::esplora::EsploraBlockchainConfig;
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
use bdk::blockchain::{AnyBlockchain, AnyBlockchainConfig, ConfigurableBlockchain};
#[cfg(feature = "rpc")]
use bdk::blockchain::rpc::{wallet_name_from_descriptor, Auth, RpcConfig};
use bdk::database::BatchDatabase;
use bdk::sled;
use bdk::sled::Tree;
use bdk::Wallet;
use bdk::{bitcoin, Error};
use bdk_cli::WalletSubCommand;
use bdk_cli::{CliOpts, CliSubCommand, KeySubCommand, OfflineWalletSubCommand, WalletOpts};
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
use bdk_cli::OnlineWalletSubCommand;
#[cfg(feature = "repl")]
use regex::Regex;
#[cfg(feature = "repl")]
const REPL_LINE_SPLIT_REGEX: &str = r#""([^"]*)"|'([^']*)'|([\w\-]+)"#;
/// REPL mode
#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(name = "", setting = AppSettings::NoBinaryName,
version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
pub enum ReplSubCommand {
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
#[structopt(flatten)]
OnlineWalletSubCommand(OnlineWalletSubCommand),
#[structopt(flatten)]
OfflineWalletSubCommand(OfflineWalletSubCommand),
#[structopt(flatten)]
KeySubCommand(KeySubCommand),
/// Exit REPL loop
Exit,
}
fn prepare_home_dir() -> PathBuf {
let mut dir = PathBuf::new();
dir.push(&dirs_next::home_dir().unwrap());
dir.push(".bdk-bitcoin");
if !dir.exists() {
info!("Creating home directory {}", dir.as_path().display());
fs::create_dir(&dir).unwrap();
}
#[cfg(not(feature = "compact_filters"))]
dir.push("database.sled");
#[cfg(feature = "compact_filters")]
dir.push("compact_filters");
dir
}
fn open_database(wallet_opts: &WalletOpts) -> Tree {
let mut database_path = prepare_home_dir();
database_path.push(wallet_opts.wallet.clone());
let database = sled::open(database_path).unwrap();
let tree = database.open_tree(&wallet_opts.wallet).unwrap();
debug!("database opened successfully");
tree
}
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
fn new_online_wallet<D>(
network: Network,
wallet_opts: &WalletOpts,
database: D,
) -> Result<Wallet<AnyBlockchain, D>, Error>
where
D: BatchDatabase,
{
#[cfg(feature = "electrum")]
let config = AnyBlockchainConfig::Electrum(ElectrumBlockchainConfig {
url: wallet_opts.electrum_opts.server.clone(),
socks5: wallet_opts.proxy_opts.proxy.clone(),
retry: wallet_opts.proxy_opts.retries,
timeout: wallet_opts.electrum_opts.timeout,
stop_gap: wallet_opts.electrum_opts.stop_gap,
});
#[cfg(feature = "esplora-ureq")]
let config = AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
base_url: wallet_opts.esplora_opts.server.clone(),
timeout_read: wallet_opts.esplora_opts.read_timeout,
timeout_write: wallet_opts.esplora_opts.write_timeout,
stop_gap: wallet_opts.esplora_opts.stop_gap,
proxy: wallet_opts.proxy_opts.proxy.clone(),
});
#[cfg(feature = "esplora-reqwest")]
let config = AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
base_url: wallet_opts.esplora_opts.server.clone(),
concurrency: Some(wallet_opts.esplora_opts.conc),
stop_gap: wallet_opts.esplora_opts.stop_gap,
proxy: wallet_opts.proxy_opts.proxy.clone(),
});
#[cfg(feature = "compact_filters")]
let config = {
let mut peers = vec![];
for addrs in wallet_opts.compactfilter_opts.address.clone() {
for _ in 0..wallet_opts.compactfilter_opts.conn_count {
peers.push(BitcoinPeerConfig {
address: addrs.clone(),
socks5: wallet_opts.proxy_opts.proxy.clone(),
socks5_credentials: wallet_opts.proxy_opts.proxy_auth.clone(),
})
}
}
AnyBlockchainConfig::CompactFilters(CompactFiltersBlockchainConfig {
peers,
network,
storage_dir: prepare_home_dir().into_os_string().into_string().unwrap(),
skip_blocks: Some(wallet_opts.compactfilter_opts.skip_blocks),
})
};
#[cfg(feature = "rpc")]
let config: AnyBlockchainConfig = {
let auth = Auth::UserPass {
username: wallet_opts.rpc_opts.auth.0.clone(),
password: wallet_opts.rpc_opts.auth.1.clone(),
};
// Use deterministic wallet name derived from descriptor
let wallet_name = wallet_name_from_descriptor(
&wallet_opts.descriptor[..],
wallet_opts.change_descriptor.as_deref(),
network,
&Secp256k1::new(),
)?;
let mut rpc_url = "http://".to_string();
rpc_url.push_str(&wallet_opts.rpc_opts.address[..]);
let rpc_config = RpcConfig {
url: rpc_url,
auth,
network,
wallet_name,
skip_blocks: wallet_opts.rpc_opts.skip_blocks,
};
AnyBlockchainConfig::Rpc(rpc_config)
};
let descriptor = wallet_opts.descriptor.as_str();
let change_descriptor = wallet_opts.change_descriptor.as_deref();
let wallet = Wallet::new(
descriptor,
change_descriptor,
network,
database,
AnyBlockchain::from_config(&config)?,
)?;
Ok(wallet)
}
fn new_offline_wallet<D>(
network: Network,
wallet_opts: &WalletOpts,
database: D,
) -> Result<Wallet<(), D>, Error>
where
D: BatchDatabase,
{
let descriptor = wallet_opts.descriptor.as_str();
let change_descriptor = wallet_opts.change_descriptor.as_deref();
let wallet = Wallet::new_offline(descriptor, change_descriptor, network, database)?;
Ok(wallet)
}
fn main() {
env_logger::init();
let cli_opts: CliOpts = CliOpts::from_args();
let network = cli_opts.network;
debug!("network: {:?}", network);
if network == Network::Bitcoin {
warn!("This is experimental software and not currently recommended for use on Bitcoin mainnet, proceed with caution.")
}
match handle_command(cli_opts, network) {
Ok(result) => println!("{}", result),
Err(e) => {
match e {
Error::ChecksumMismatch => error!("Descriptor checksum mismatch. Are you using a different descriptor for an already defined wallet name? (if you are not specifying the wallet name it defaults to 'main')"),
e => error!("{}", e.to_string()),
}
},
}
}
fn handle_command(cli_opts: CliOpts, network: Network) -> Result<String, Error> {
let result = match cli_opts.subcommand {
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
CliSubCommand::Wallet {
wallet_opts,
subcommand: WalletSubCommand::OnlineWalletSubCommand(online_subcommand),
} => {
let database = open_database(&wallet_opts);
let wallet = new_online_wallet(network, &wallet_opts, database)?;
let result = bdk_cli::handle_online_wallet_subcommand(&wallet, online_subcommand)?;
serde_json::to_string_pretty(&result)?
}
CliSubCommand::Wallet {
wallet_opts,
subcommand: WalletSubCommand::OfflineWalletSubCommand(offline_subcommand),
} => {
let database = open_database(&wallet_opts);
let wallet = new_offline_wallet(network, &wallet_opts, database)?;
let result = bdk_cli::handle_offline_wallet_subcommand(
&wallet,
&wallet_opts,
offline_subcommand,
)?;
serde_json::to_string_pretty(&result)?
}
CliSubCommand::Key {
subcommand: key_subcommand,
} => {
let result = bdk_cli::handle_key_subcommand(network, key_subcommand)?;
serde_json::to_string_pretty(&result)?
}
#[cfg(feature = "compiler")]
CliSubCommand::Compile {
policy,
script_type,
} => {
let result = bdk_cli::handle_compile_subcommand(network, policy, script_type)?;
serde_json::to_string_pretty(&result)?
}
#[cfg(feature = "repl")]
CliSubCommand::Repl { wallet_opts } => {
let database = open_database(&wallet_opts);
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
let wallet = new_online_wallet(network, &wallet_opts, database)?;
#[cfg(not(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
)))]
let wallet = new_offline_wallet(network, &wallet_opts, database)?;
let mut rl = Editor::<()>::new();
// if rl.load_history("history.txt").is_err() {
// println!("No previous history.");
// }
let split_regex =
Regex::new(REPL_LINE_SPLIT_REGEX).map_err(|e| Error::Generic(e.to_string()))?;
loop {
let readline = rl.readline(">> ");
match readline {
Ok(line) => {
if line.trim() == "" {
continue;
}
rl.add_history_entry(line.as_str());
let split_line: Vec<&str> = split_regex
.captures_iter(&line)
.map(|c| {
c.get(1)
.or_else(|| c.get(2))
.or_else(|| c.get(3))
.unwrap()
.as_str()
})
.collect();
let repl_subcommand: Result<ReplSubCommand, clap::Error> =
ReplSubCommand::from_iter_safe(split_line);
debug!("repl_subcommand = {:?}", repl_subcommand);
if let Err(err) = repl_subcommand {
println!("{}", err.message);
continue;
}
let repl_subcommand = repl_subcommand.unwrap();
let result = match repl_subcommand {
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "compact_filters",
feature = "rpc"
))]
ReplSubCommand::OnlineWalletSubCommand(online_subcommand) => {
bdk_cli::handle_online_wallet_subcommand(&wallet, online_subcommand)
}
ReplSubCommand::OfflineWalletSubCommand(offline_subcommand) => {
bdk_cli::handle_offline_wallet_subcommand(
&wallet,
&wallet_opts,
offline_subcommand,
)
}
ReplSubCommand::KeySubCommand(key_subcommand) => {
bdk_cli::handle_key_subcommand(network, key_subcommand)
}
ReplSubCommand::Exit => break,
};
println!(
"{}",
serde_json::to_string_pretty(&result.unwrap()).unwrap()
);
}
Err(ReadlineError::Interrupted) => continue,
Err(ReadlineError::Eof) => break,
Err(err) => {
println!("{:?}", err);
break;
}
}
}
// rl.save_history("history.txt").unwrap();
"Exiting REPL".to_string()
}
};
Ok(result)
}
#[cfg(test)]
mod test {
use crate::REPL_LINE_SPLIT_REGEX;
use regex::Regex;
#[test]
fn test_regex_double_quotes() {
let split_regex = Regex::new(REPL_LINE_SPLIT_REGEX).unwrap();
let line = r#"restore -m "word1 word2 word3" -p 'test! 123 -test' "#;
let split_line: Vec<&str> = split_regex
.captures_iter(&line)
.map(|c| {
c.get(1)
.or_else(|| c.get(2))
.or_else(|| c.get(3))
.unwrap()
.as_str()
})
.collect();
assert_eq!(
vec!(
"restore",
"-m",
"word1 word2 word3",
"-p",
"test! 123 -test"
),
split_line
);
}
#[test]
fn test_regex_single_quotes() {
let split_regex = Regex::new(REPL_LINE_SPLIT_REGEX).unwrap();
let line = r#"restore -m 'word1 word2 word3' -p "test *123 -test" "#;
let split_line: Vec<&str> = split_regex
.captures_iter(&line)
.map(|c| {
c.get(1)
.or_else(|| c.get(2))
.or_else(|| c.get(3))
.unwrap()
.as_str()
})
.collect();
assert_eq!(
vec!(
"restore",
"-m",
"word1 word2 word3",
"-p",
"test *123 -test"
),
split_line
);
}
}
|
use super::types::{Arr1d, Arr2d};
use ndarray::{Array, Array1, Axis, RemoveAxis};
extern crate ndarray_stats;
// use ndarray_stats::SummaryStatisticsExt;
pub fn reverse_one_hot(one_hot_target: &Arr2d) -> Array1<usize> {
one_hot_target.map_axis(Axis(1), |v| {
v.iter()
.position(|x| *x == 1.0)
.expect("found empty target!")
})
}
pub fn cross_entropy_error(pred: &Arr2d, one_hot_target: &Arr2d) -> Arr1d {
// cross_entropy_error_target(pred, reverse_one_hot(one_hot_target)
-(pred.mapv(|x| (x + 1e-7).ln()) * one_hot_target).sum_axis(Axis(1))
}
pub fn softmax(input: Arr2d) -> Arr2d {
// input - input.max(Axis(1))
let input = input.mapv(|x| x.exp());
let sum = input.sum_axis(Axis(1));
input / sum.insert_axis(Axis(1))
}
pub fn softmaxd<D: RemoveAxis>(input: Array<f32, D>) -> Array<f32, D> {
// input - input.max(Axis(1))
let ndim = input.ndim();
let input = input.mapv(|x| x.exp());
let sum = input.sum_axis(Axis(ndim - 1));
input / sum.insert_axis(Axis(ndim - 1))
}
pub fn cross_entropy_error_target(pred: &Arr2d, target: &Array1<usize>) -> f32 {
let mut entropy = Array::zeros(target.len());
for (i, e) in entropy.iter_mut().enumerate() {
*e = -(pred[[i, target[i]]] + 1e-7).ln()
}
entropy
.mean()
.expect("error computing cross_entropy_error_target")
}
/// 2つのベクトルの角度のコサインを返す
/// 1~-1の類似度を表す
pub fn cos_similarity(x: Arr1d, y: Arr1d) -> f32 {
let nx = x.mapv(|a| a.powi(2)).sum().sqrt() + 1e-7;
let ny = y.mapv(|a| a.powi(2)).sum().sqrt() + 1e-7;
x.dot(&y) / (nx * ny)
}
/// 単純に内積を取る
pub fn cos(u: &Arr1d, v: &Arr1d) -> f32 {
u.dot(v)
}
pub fn normalize<D: RemoveAxis>(m: Array<f32, D>) -> Array<f32, D> {
let d = m.shape().len();
let nm = m
.mapv(|a| a * a)
.sum_axis(Axis(d - 1))
.mapv(f32::sqrt)
.insert_axis(Axis(d - 1))
+ 1e-7;
m / nm
}
|
use std::io::Error;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
//use std::collections::HashSet;
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;
fn read_input(filename: &str) -> Result<String, Error> {
let mut input = String::new();
File::open(filename)?.read_to_string(&mut input)?;
return Ok(input);
}
fn main() {
match read_input("input.txt") {
Ok(input) => {
//let (part1, part2) = answers("s1,x3/4,pe/b");
let (part1, part2) = answers(&input);
println!("Part 1 answer: {}", part1);
println!("Part 2 answer: {}", part2);
},
Err(e) => println!("Error: {}", e),
}
}
fn answers(input: &str) -> (String, String) {
let mut dance = Dance {
state: vec![
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'
//'a', 'b', 'c', 'd', 'e',
],
};
let moves = Dance::moves_from_input(input);
let order0 = dance.order();
dance.do_moves(&moves);
let answer1 = dance.order();
for i in 0..999_999_999 {
dance.do_moves(&moves);
//if dance.order() == "abcdefghijklmop" { println!("omg {}", i); }
//if i % 10_000 == 0 { println!("{}", i); }
}
let final_order = dance.order();
return (answer1, final_order);
}
lazy_static! {
static ref X_REGEX: Regex = Regex::new(r"(?x)
x
(\d+)
/
(\d+)
").unwrap();
static ref P_REGEX: Regex = Regex::new(r"(?x)
p
([a-z])
/
([a-z])
").unwrap();
static ref S_REGEX: Regex = Regex::new(r"(?x)
s
(\d+)
").unwrap();
}
struct DanceMove {
move_type: char,
s_arg: usize,
x_arg_0: usize,
x_arg_1: usize,
p_arg_0: char,
p_arg_1: char,
}
impl DanceMove {
fn from_str(move_str: &str) -> Option<DanceMove> {
match X_REGEX.captures(move_str) {
Some(caps) => {
let arg_0 = caps.get(1).unwrap().as_str().parse::<usize>().ok().unwrap();
let arg_1 = caps.get(2).unwrap().as_str().parse::<usize>().ok().unwrap();
return Some(DanceMove {
move_type: 'x',
x_arg_0: arg_0,
x_arg_1: arg_1,
s_arg: 0,
p_arg_0: '\0',
p_arg_1: '\0',
});
},
None => {
match P_REGEX.captures(move_str) {
Some(caps) => {
let arg_0 = caps.get(1).unwrap().as_str().chars().nth(0).unwrap();
let arg_1 = caps.get(2).unwrap().as_str().chars().nth(0).unwrap();
return Some(DanceMove {
move_type: 'p',
p_arg_0: arg_0,
p_arg_1: arg_1,
s_arg: 0,
x_arg_0: 0,
x_arg_1: 0,
});
},
None => {
match S_REGEX.captures(move_str) {
Some(caps) => {
let arg = caps.get(1).unwrap().as_str().parse::<usize>().ok().unwrap();
return Some(DanceMove {
move_type: 's',
s_arg: arg,
p_arg_0: '\0',
p_arg_1: '\0',
x_arg_0: 0,
x_arg_1: 0,
});
},
None => { /* bad move_str */ }
}
}
}
}
}
return None;
}
}
struct Dance {
state: Vec<char>,
}
impl Dance {
fn apply_output_map(&mut self, output_map: &HashMap<usize,usize>) -> () {
let mut new_state: Vec<char> = Vec::new();
for i in 0..output_map.len() {
new_state.push(self.state[*(output_map.get(&i).unwrap())]);
}
self.state = new_state;
//println!("{}", self.order());
}
fn do_moves(&mut self, moves: &Vec<DanceMove>) -> () {
for m in moves {
self.do_move(m);
}
}
fn moves_from_input(input: &str) -> Vec<DanceMove> {
return input
.split(",")
.flat_map(|s| DanceMove::from_str(s))
.collect();
}
fn order(&self) -> String {
let mut order = String::from("");
for i in 0..self.state.len() {
order.push(self.state[i]);
}
return order;
}
fn do_move(&mut self, m: &DanceMove) -> () {
if m.move_type == 'x' {
self.move_x(m.x_arg_0, m.x_arg_1);
}
else if m.move_type == 'p' {
self.move_p(m.p_arg_0, m.p_arg_1);
}
else if m.move_type == 's' {
self.move_s(m.s_arg);
}
}
fn index_of(&self, x: char) -> usize {
for i in 0..self.state.len() {
if self.state[i] == x { return i; }
}
return 0;
}
fn move_x(&mut self, a: usize, b: usize) -> () {
let a_val = self.state[a];
self.state[a] = self.state[b];
self.state[b] = a_val;
}
fn move_p(&mut self, a: char, b: char) -> () {
let a_i = self.index_of(a);
let b_i = self.index_of(b);
self.move_x(a_i, b_i);
}
fn move_s(&mut self, n: usize) -> () {
if n < 1 { return; }
let len = self.state.len();
let last_val = self.state[len-1];
let mut j = len-1;
while j > 0 {
self.state[j] = self.state[j-1];
j -= 1;
}
self.state[0] = last_val;
self.move_s(n-1);
}
}
|
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Macro for declaring a module error.
#[doc(hidden)]
pub use frame_metadata::{DecodeDifferent, ErrorMetadata, ModuleErrorMetadata};
#[doc(hidden)]
pub use sp_runtime::traits::{BadOrigin, LookupError};
/// Declare an error type for a runtime module.
///
/// `decl_error!` supports only variants that do not hold any data. The dispatchable
/// functions return [`DispatchResult`](sp_runtime::DispatchResult). The error type
/// implements `From<ErrorType> for DispatchResult` to make the error type usable as error
/// in the dispatchable functions.
///
/// It is required that the error type is registered in `decl_module!` to make the error
/// exported in the metadata.
///
/// # Usage
///
/// ```
/// # use frame_support::{decl_error, decl_module};
/// #
/// decl_error! {
/// /// Errors that can occur in my module.
/// pub enum MyError for Module<T: Trait> {
/// /// Hey this is an error message that indicates bla.
/// MyCoolErrorMessage,
/// /// You are just not cool enough for my module!
/// YouAreNotCoolEnough,
/// }
/// }
///
/// # use frame_system::Trait;
///
/// // You need to register the error type in `decl_module!` as well to make the error
/// // exported in the metadata.
///
/// decl_module! {
/// pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// type Error = MyError<T>;
///
/// #[weight = 0]
/// fn do_something(origin) -> frame_support::dispatch::DispatchResult {
/// Err(MyError::<T>::YouAreNotCoolEnough.into())
/// }
/// }
/// }
///
/// # fn main() {}
/// ```
///
/// For instantiable modules you also need to give the instance generic type and bound to the
/// error declaration.
#[macro_export]
macro_rules! decl_error {
(
$(#[$attr:meta])*
pub enum $error:ident
for $module:ident<
$generic:ident: $trait:path
$(, $inst_generic:ident: $instance:path)?
>
{
$(
$( #[doc = $doc_attr:tt] )*
$name:ident
),*
$(,)?
}
) => {
$(#[$attr])*
pub enum $error<$generic: $trait $(, $inst_generic: $instance)?> {
#[doc(hidden)]
__Ignore(
$crate::sp_std::marker::PhantomData<($generic, $( $inst_generic)?)>,
$crate::Never,
),
$(
$( #[doc = $doc_attr] )*
$name
),*
}
impl<$generic: $trait $(, $inst_generic: $instance)?> $crate::sp_std::fmt::Debug
for $error<$generic $(, $inst_generic)?>
{
fn fmt(&self, f: &mut $crate::sp_std::fmt::Formatter<'_>) -> $crate::sp_std::fmt::Result {
f.write_str(self.as_str())
}
}
impl<$generic: $trait $(, $inst_generic: $instance)?> $error<$generic $(, $inst_generic)?> {
fn as_u8(&self) -> u8 {
$crate::decl_error! {
@GENERATE_AS_U8
self
$error
{}
0,
$( $name ),*
}
}
fn as_str(&self) -> &'static str {
match self {
Self::__Ignore(_, _) => unreachable!("`__Ignore` can never be constructed"),
$(
$error::$name => stringify!($name),
)*
}
}
}
impl<$generic: $trait $(, $inst_generic: $instance)?> From<$error<$generic $(, $inst_generic)?>>
for &'static str
{
fn from(err: $error<$generic $(, $inst_generic)?>) -> &'static str {
err.as_str()
}
}
impl<$generic: $trait $(, $inst_generic: $instance)?> From<$error<$generic $(, $inst_generic)?>>
for $crate::sp_runtime::DispatchError
{
fn from(err: $error<$generic $(, $inst_generic)?>) -> Self {
let index = <$generic::PalletInfo as $crate::traits::PalletInfo>
::index::<$module<$generic $(, $inst_generic)?>>()
.expect("Every active module has an index in the runtime; qed") as u8;
$crate::sp_runtime::DispatchError::Module {
index,
error: err.as_u8(),
message: Some(err.as_str()),
}
}
}
impl<$generic: $trait $(, $inst_generic: $instance)?> $crate::error::ModuleErrorMetadata
for $error<$generic $(, $inst_generic)?>
{
fn metadata() -> &'static [$crate::error::ErrorMetadata] {
&[
$(
$crate::error::ErrorMetadata {
name: $crate::error::DecodeDifferent::Encode(stringify!($name)),
documentation: $crate::error::DecodeDifferent::Encode(&[
$( $doc_attr ),*
]),
}
),*
]
}
}
};
(@GENERATE_AS_U8
$self:ident
$error:ident
{ $( $generated:tt )* }
$index:expr,
$name:ident
$( , $rest:ident )*
) => {
$crate::decl_error! {
@GENERATE_AS_U8
$self
$error
{
$( $generated )*
$error::$name => $index,
}
$index + 1,
$( $rest ),*
}
};
(@GENERATE_AS_U8
$self:ident
$error:ident
{ $( $generated:tt )* }
$index:expr,
) => {
match $self {
$error::__Ignore(_, _) => unreachable!("`__Ignore` can never be constructed"),
$( $generated )*
}
}
}
|
use crate::grid::builder::Builder;
use std::borrow::Cow;
use terminal::Terminal;
pub struct Alert {
pub message: Cow<'static, str>,
pub clear_delay: usize,
}
impl Alert {
pub fn new(message: Cow<'static, str>) -> Self {
Self {
message,
clear_delay: 75,
}
}
/// Clears the previous alert.
pub fn clear(&mut self, terminal: &mut Terminal, builder: &mut Builder) {
crate::set_cursor_for_top_text(terminal, &builder, self.message.len(), 0, None);
for _ in 0..self.message.len() {
terminal.write(" ");
}
}
/// Draws an alert above the grid.
pub fn draw(&self, terminal: &mut Terminal, builder: &Builder) {
crate::set_cursor_for_top_text(terminal, &builder, self.message.len(), 0, None);
terminal.write(&self.message);
}
}
|
use crate::todo_item::TodoItem;
use crate::utils::StatefulList;
use std::fmt::{Display, Formatter, Result};
use std::sync::{Arc, Mutex};
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AppStage {
Default,
CreateItem,
UpdateItem,
Filter,
}
pub struct App {
pub list: StatefulList<TodoItem>,
pub stage: Arc<Mutex<AppStage>>,
pub item_name_input: String,
pub filter_term: String,
pub sorting_order: AppSorting,
}
impl App {
pub fn new(items: Vec<TodoItem>) -> App {
let mut app = App {
list: StatefulList::new(items),
stage: Arc::new(Mutex::new(AppStage::Default)),
item_name_input: String::new(),
sorting_order: AppSorting::ByDate(SortingOrder::Ascending),
filter_term: String::new(),
};
app.sort_by_date(SortingOrder::Ascending);
app.select_first_task_or_none();
app
}
pub fn add_new_item(&mut self) {
if self.item_name_input.is_empty() {
return;
}
self.list.items.push(TodoItem::new(&self.item_name_input));
}
pub fn update_item(&mut self) {
if self.item_name_input.is_empty() {
return;
}
match self.list.get_selected_item() {
None => {}
Some(selected_item) => {
for item in &mut self.list.items {
if item.id == selected_item.id {
item.set_name(self.item_name_input.as_str());
}
}
}
}
}
pub fn toggle_task(&mut self) {
if let Some(selected_item) = self.list.get_selected_item() {
for item in &mut self.list.items {
if item.id == selected_item.id {
item.set_completion(!item.completed);
}
}
};
}
pub fn remove_task(&mut self) {
if let Some(selected_item) = self.list.get_selected_item() {
let filtered_items: Vec<TodoItem> = self
.list
.items
.iter()
.filter(|item| item.id != selected_item.id)
.cloned()
.collect();
self.list = StatefulList::new(filtered_items);
self.select_first_task_or_none();
}
}
pub fn set_stage(&mut self, stage: AppStage) {
self.reset_item_name_input();
match stage {
AppStage::UpdateItem => {
if let Some(selected_item) = self.list.get_selected_item() {
self.item_name_input = selected_item.name;
*self.stage.lock().unwrap() = stage;
}
}
_ => *self.stage.lock().unwrap() = stage,
}
}
fn set_sorting_order(&mut self, order: AppSorting) {
self.sorting_order = order.clone();
match order {
AppSorting::ByDate(order) => self.sort_by_date(order),
AppSorting::ByCompletion(order) => self.sort_by_completion(order),
};
}
pub fn toggle_sorting(&mut self) {
let sorting_rotation_list = [
AppSorting::ByDate(SortingOrder::Ascending),
AppSorting::ByDate(SortingOrder::Descending),
AppSorting::ByCompletion(SortingOrder::Ascending),
AppSorting::ByCompletion(SortingOrder::Descending),
];
let current_sorting_index = sorting_rotation_list
.iter()
.position(|sorting| sorting.eq(&self.sorting_order))
.unwrap();
let next_sorting = match sorting_rotation_list.get(current_sorting_index + 1) {
None => sorting_rotation_list.get(0).unwrap(),
Some(order) => order,
};
self.set_sorting_order(next_sorting.clone());
}
pub fn item_input_add_character(&mut self, letter: char) {
self.item_name_input = format!("{}{}", self.item_name_input, letter);
}
pub fn item_input_remove_character(&mut self) {
self.item_name_input.pop();
}
pub fn reset_item_name_input(&mut self) {
self.item_name_input = String::new()
}
pub fn filter_term_add_character(&mut self, letter: char) {
self.filter_term = format!("{}{}", self.filter_term, letter);
}
pub fn filter_term_remove_character(&mut self) {
self.filter_term.pop();
}
pub fn get_stage_clone(&self) -> AppStage {
*self.stage.clone().lock().unwrap()
}
pub fn get_filtered_items(&self) -> Vec<(usize, TodoItem)> {
let mut items: Vec<(usize, TodoItem)> = vec![];
for (index, item) in self.list.items.iter().enumerate() {
if item
.name
.to_lowercase()
.contains(&self.filter_term.to_lowercase())
{
items.push((index, item.clone()));
}
}
items
}
fn sort_by_date(&mut self, sorting_order: SortingOrder) {
self.list
.items
.sort_by(|item_a, item_b| match sorting_order {
SortingOrder::Ascending => item_a.updated_date.cmp(&item_b.updated_date),
SortingOrder::Descending => item_a.updated_date.cmp(&item_b.updated_date).reverse(),
});
}
fn sort_by_completion(&mut self, sorting_order: SortingOrder) {
self.list
.items
.sort_by(|item_a, item_b| match sorting_order {
SortingOrder::Ascending => item_a.completed.cmp(&item_b.completed).reverse(),
SortingOrder::Descending => item_a.completed.cmp(&item_b.completed),
});
}
fn select_first_task_or_none(&mut self) {
if !self.list.items.is_empty() {
self.list.state.select(Some(0));
} else {
self.list.state.select(None);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
static TASK_A_NAME: &str = "A";
static TASK_B_NAME: &str = "B";
#[test]
fn it_creates_app() {
let items = create_todo_items();
let app = App::new(items.clone());
assert_eq!(app.list.items.len(), items.len());
assert_eq!(app.list.items[0].id, items[0].id);
assert_eq!(
app.sorting_order,
AppSorting::ByDate(SortingOrder::Ascending)
);
assert_eq!(*app.stage.lock().unwrap(), AppStage::Default);
assert_eq!(app.item_name_input, "");
assert_eq!(app.filter_term, "");
// Correct item is selected
assert_eq!(app.list.get_selected_item().unwrap().id, items[0].id);
}
#[test]
fn it_add_new_item() {
let mut app = App::new(vec![]);
app.item_input_add_character('a');
assert_eq!(app.item_name_input, "a");
app.add_new_item();
assert_eq!(app.list.items[0].name, "a");
}
#[test]
fn it_should_edit_existing_item() {
let mut app = App::new(vec![TodoItem::new(TASK_A_NAME)]);
app.item_input_add_character('a');
assert_eq!(app.item_name_input, "a");
app.update_item();
assert_eq!(app.list.items.len(), 1);
assert_eq!(app.list.items[0].name, "a");
}
#[test]
fn it_should_not_add_empty_item() {
let mut app = App::new(vec![]);
app.add_new_item();
assert_eq!(app.list.items.len(), 0);
}
#[test]
fn it_removes_selected_item() {
let items = create_todo_items();
let mut app = App::new(vec![items[0].clone()]);
app.remove_task();
assert_eq!(app.list.items.len(), 0);
}
#[test]
fn it_toggles_sorting() {
let items = create_todo_items();
let mut app = App::new(items);
let item_id = app.list.items[0].set_completion(true).id;
app.toggle_sorting();
assert_eq!(
app.sorting_order,
AppSorting::ByDate(SortingOrder::Descending)
);
app.toggle_sorting();
assert_eq!(
app.sorting_order,
AppSorting::ByCompletion(SortingOrder::Ascending)
);
assert_eq!(app.list.items[0].id, item_id);
app.toggle_sorting();
assert_eq!(
app.sorting_order,
AppSorting::ByCompletion(SortingOrder::Descending)
);
assert_eq!(app.list.items[1].id, item_id);
app.toggle_sorting();
assert_eq!(
app.sorting_order,
AppSorting::ByDate(SortingOrder::Ascending)
);
}
#[test]
fn it_filters_items() {
let items = create_todo_items();
let mut app = App::new(items);
app.filter_term_add_character('a');
assert_eq!(app.filter_term, "a");
assert_eq!(app.list.items.len(), 2);
assert_eq!(app.get_filtered_items().len(), 1);
}
#[test]
fn it_should_keep_initial_list_enumeration() {
let items = create_todo_items();
let mut app = App::new(items);
app.filter_term_add_character('b');
assert_eq!(app.filter_term, "b");
assert_eq!(app.get_filtered_items()[0].0, 1);
assert_eq!(app.get_filtered_items()[0].1.name, TASK_B_NAME);
}
fn create_todo_items() -> Vec<TodoItem> {
vec![
TodoItem::new(&(*TASK_A_NAME)),
TodoItem::new(&(*TASK_B_NAME)),
]
}
}
#[derive(PartialEq, Debug, Clone)]
pub enum AppSorting {
ByDate(SortingOrder),
ByCompletion(SortingOrder),
}
impl Display for AppSorting {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(
f,
"{}",
match &self {
AppSorting::ByDate(SortingOrder::Ascending) => "Most recently updated first",
AppSorting::ByDate(SortingOrder::Descending) => "Least recently updated first",
AppSorting::ByCompletion(SortingOrder::Ascending) => "Done first",
AppSorting::ByCompletion(SortingOrder::Descending) => "Undone first",
}
)
}
}
#[derive(PartialEq, Debug, Clone)]
pub enum SortingOrder {
Ascending,
Descending,
}
|
// Copyright (c) 2020 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
//! macro functions.
macro_rules! cfg_sync {
($($item:item)*) => {
$(
#[cfg(feature = "sync")]
#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
$item
)*
}
}
macro_rules! cfg_async {
($($item:item)*) => {
$(
#[cfg(all(feature = "async", target_family="unix"))]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
$item
)*
}
}
|
use crate::domain::repository::IRepository;
use crate::{command::CommandError, domain::model::Favorite};
use std::env;
use std::fs;
use std::path::Path;
pub enum WhereToAdd<'a> {
Path(&'a Path),
CurrentDirectory,
}
pub fn add_favorite<T: IRepository>(
repo: &T,
key: String,
path: WhereToAdd,
) -> anyhow::Result<Favorite> {
if repo.is_exist(&key)? {
return Err(CommandError::GivenKeyIsAlreadyExists.into());
}
match path {
WhereToAdd::Path(path) => add_given_path_to_db(repo, key, path),
WhereToAdd::CurrentDirectory => add_current_path_to_db(repo, key),
}
}
fn add_given_path_to_db<T: IRepository>(
repo: &T,
key: String,
path: &Path,
) -> anyhow::Result<Favorite> {
if !path.exists() {
return Err(CommandError::PathNotFound.into());
}
let favorite = Favorite::new(
key,
fs::canonicalize(path)?
.as_path()
.to_str()
.unwrap()
.to_owned(),
);
repo.add(&favorite).map(|_| Ok(favorite))?
}
fn add_current_path_to_db<T: IRepository>(repo: &T, key: String) -> anyhow::Result<Favorite> {
match env::current_dir() {
Ok(current_path) => {
let favorite: anyhow::Result<Favorite> = current_path
.as_path()
.to_str()
.map(|path| Favorite::new(key, path.to_owned()))
.ok_or_else(|| CommandError::InvalidPath.into());
repo.add(&favorite?)
}
Err(e) => Err(e.into()),
}
}
|
extern crate pretty_hash;
#[test]
fn formats_stuff() {
let hash = pretty_hash::fmt(b"1234").unwrap();
assert_eq!(hash, "31323334");
let hash = pretty_hash::fmt(b"12345").unwrap();
assert_eq!(hash, "313233..35");
let hash = pretty_hash::fmt(b"\x01\x02\x03\x04").unwrap();
assert_eq!(hash, "01020304");
let hash = pretty_hash::fmt(b"\x01\x02\x03\x04\x05").unwrap();
assert_eq!(hash, "010203..05");
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImportImageParameters {
pub source: ImportSource,
#[serde(rename = "targetTags", default, skip_serializing_if = "Vec::is_empty")]
pub target_tags: Vec<String>,
#[serde(rename = "untaggedTargetRepositories", default, skip_serializing_if = "Vec::is_empty")]
pub untagged_target_repositories: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<import_image_parameters::Mode>,
}
pub mod import_image_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Mode {
NoForce,
Force,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImportSource {
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "registryUri", default, skip_serializing_if = "Option::is_none")]
pub registry_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credentials: Option<ImportSourceCredentials>,
#[serde(rename = "sourceImage")]
pub source_image: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImportSourceCredentials {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
pub password: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryNameCheckRequest {
pub name: String,
#[serde(rename = "type")]
pub type_: registry_name_check_request::Type,
}
pub mod registry_name_check_request {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Microsoft.ContainerRegistry/registries")]
MicrosoftContainerRegistryRegistries,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryNameStatus {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<OperationDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplayDefinition>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<OperationPropertiesDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplayDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationPropertiesDefinition {
#[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")]
pub service_specification: Option<OperationServiceSpecificationDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationServiceSpecificationDefinition {
#[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")]
pub metric_specifications: Vec<OperationMetricSpecificationDefinition>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationMetricSpecificationDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")]
pub display_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")]
pub aggregation_type: Option<String>,
#[serde(rename = "internalMetricName", default, skip_serializing_if = "Option::is_none")]
pub internal_metric_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Registry {
#[serde(flatten)]
pub resource: Resource,
pub sku: Sku,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RegistryProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
pub name: sku::Name,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<sku::Tier>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
Classic,
Basic,
Standard,
Premium,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tier {
Classic,
Basic,
Standard,
Premium,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryProperties {
#[serde(rename = "loginServer", default, skip_serializing_if = "Option::is_none")]
pub login_server: Option<String>,
#[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")]
pub creation_date: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<registry_properties::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<Status>,
#[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")]
pub admin_user_enabled: Option<bool>,
#[serde(rename = "storageAccount", default, skip_serializing_if = "Option::is_none")]
pub storage_account: Option<StorageAccountProperties>,
#[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")]
pub network_rule_set: Option<NetworkRuleSet>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policies: Option<Policies>,
}
pub mod registry_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Creating,
Updating,
Deleting,
Succeeded,
Failed,
Canceled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Status {
#[serde(rename = "displayStatus", default, skip_serializing_if = "Option::is_none")]
pub display_status: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccountProperties {
pub id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkRuleSet {
#[serde(rename = "defaultAction")]
pub default_action: network_rule_set::DefaultAction,
#[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_network_rules: Vec<VirtualNetworkRule>,
#[serde(rename = "ipRules", default, skip_serializing_if = "Vec::is_empty")]
pub ip_rules: Vec<IpRule>,
}
pub mod network_rule_set {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DefaultAction {
Allow,
Deny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Policies {
#[serde(rename = "quarantinePolicy", default, skip_serializing_if = "Option::is_none")]
pub quarantine_policy: Option<QuarantinePolicy>,
#[serde(rename = "trustPolicy", default, skip_serializing_if = "Option::is_none")]
pub trust_policy: Option<TrustPolicy>,
#[serde(rename = "retentionPolicy", default, skip_serializing_if = "Option::is_none")]
pub retention_policy: Option<RetentionPolicy>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkRule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<virtual_network_rule::Action>,
pub id: String,
}
pub mod virtual_network_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Action {
Allow,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IpRule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<ip_rule::Action>,
pub value: String,
}
pub mod ip_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Action {
Allow,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QuarantinePolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<quarantine_policy::Status>,
}
pub mod quarantine_policy {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrustPolicy {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<trust_policy::Type>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<trust_policy::Status>,
}
pub mod trust_policy {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
Notary,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RetentionPolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub days: Option<i32>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<retention_policy::Status>,
}
pub mod retention_policy {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RegistryPropertiesUpdateParameters>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryPropertiesUpdateParameters {
#[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")]
pub admin_user_enabled: Option<bool>,
#[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")]
pub network_rule_set: Option<NetworkRuleSet>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policies: Option<Policies>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Registry>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryListCredentialsResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub passwords: Vec<RegistryPassword>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryPassword {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<registry_password::Name>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
pub mod registry_password {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
#[serde(rename = "password")]
Password,
#[serde(rename = "password2")]
Password2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegenerateCredentialParameters {
pub name: regenerate_credential_parameters::Name,
}
pub mod regenerate_credential_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
#[serde(rename = "password")]
Password,
#[serde(rename = "password2")]
Password2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryUsageListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RegistryUsage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistryUsage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
#[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")]
pub current_value: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<registry_usage::Unit>,
}
pub mod registry_usage {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Unit {
Count,
Bytes,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Replication {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ReplicationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReplicationProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<replication_properties::ProvisioningState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<Status>,
}
pub mod replication_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Creating,
Updating,
Deleting,
Succeeded,
Failed,
Canceled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReplicationUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReplicationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Replication>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Webhook {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebhookProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<webhook_properties::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
pub actions: Vec<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<webhook_properties::ProvisioningState>,
}
pub mod webhook_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Creating,
Updating,
Deleting,
Succeeded,
Failed,
Canceled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookCreateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebhookPropertiesCreateParameters>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookPropertiesCreateParameters {
#[serde(rename = "serviceUri")]
pub service_uri: String,
#[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")]
pub custom_headers: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<webhook_properties_create_parameters::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
pub actions: Vec<String>,
}
pub mod webhook_properties_create_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<WebhookPropertiesUpdateParameters>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookPropertiesUpdateParameters {
#[serde(rename = "serviceUri", default, skip_serializing_if = "Option::is_none")]
pub service_uri: Option<String>,
#[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")]
pub custom_headers: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<webhook_properties_update_parameters::Status>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<String>,
}
pub mod webhook_properties_update_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "enabled")]
Enabled,
#[serde(rename = "disabled")]
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WebhookListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Webhook>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CallbackConfig {
#[serde(rename = "serviceUri")]
pub service_uri: String,
#[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")]
pub custom_headers: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Event>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Event {
#[serde(flatten)]
pub event_info: EventInfo,
#[serde(rename = "eventRequestMessage", default, skip_serializing_if = "Option::is_none")]
pub event_request_message: Option<EventRequestMessage>,
#[serde(rename = "eventResponseMessage", default, skip_serializing_if = "Option::is_none")]
pub event_response_message: Option<EventResponseMessage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventRequestMessage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<EventContent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub headers: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(rename = "requestUri", default, skip_serializing_if = "Option::is_none")]
pub request_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventResponseMessage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub headers: Option<serde_json::Value>,
#[serde(rename = "reasonPhrase", default, skip_serializing_if = "Option::is_none")]
pub reason_phrase: Option<String>,
#[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")]
pub status_code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventContent {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request: Option<Request>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actor: Option<Actor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<Source>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Target {
#[serde(rename = "mediaType", default, skip_serializing_if = "Option::is_none")]
pub media_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub length: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Request {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub addr: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub useragent: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Actor {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Source {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub addr: Option<String>,
#[serde(rename = "instanceID", default, skip_serializing_if = "Option::is_none")]
pub instance_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
|
use actix::Message;
use kosem_webapi::Uuid;
use crate::role_actors::{HumanActor, JoinerActor, ProcedureActor};
#[derive(Clone, Message)]
#[rtype(result = "()")]
pub struct ConnectionClosed;
#[derive(Message)]
#[rtype(result = "()")]
pub struct RpcMessage {
pub method: String,
pub params: serde_value::Value,
}
impl RpcMessage {
pub fn new(method: impl Into<String>, params: impl serde::Serialize) -> Self {
RpcMessage {
method: method.into(),
params: serde_value::to_value(params).unwrap(),
}
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub enum SetRole {
Procedure(actix::Addr<ProcedureActor>),
Human(actix::Addr<JoinerActor>),
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct AddHumanActor {
pub request_uid: Uuid,
pub addr: actix::Addr<HumanActor>,
}
|
use proconio::{input, marker::Bytes};
fn main() {
input! {
k: u64,
a: Bytes,
b: Bytes,
}
let a = a.iter().rev().enumerate().fold(0, |s, (i, e)| s + ((e - b'0') as u64) * k.pow(i as u32));
let b = b.iter().rev().enumerate().fold(0, |s, (i, e)| s + ((e - b'0') as u64) * k.pow(i as u32));
println!("{}", a * b);
}
|
#![deny(missing_docs)]
//! A simple key/value store.
use std::collections::HashMap;
/// The type for storing key-value pairs. The key and the value are both String, and each key must be assigned with a value.
///
/// You can store the key-value pair by set() method, and get a key's value by get() method. This is all we support now.
#[derive(Default)]
pub struct KvStore {
store: HashMap<String, String>,
}
impl KvStore {
/// Creates a KvStore
pub fn new() -> Self {
KvStore {
store: HashMap::new(),
}
}
/// Store a key with it's value, this will store a key and it's value to the storage.
/// If the key has already been exist, the value will be overwrited.
///
/// # Example
///
/// ```
/// use kvs::KvStore;
/// let mut store = KvStore::new();
/// store.set("key".to_owned(), "value1".to_owned());
/// assert_eq!(Some("value1".to_owned()), store.get("key".to_owned()));
/// store.set("key".to_owned(), "value2".to_owned());
/// assert_eq!(Some("value2".to_owned()), store.get("key".to_owned()));
/// ```
pub fn set(&mut self, key: String, value: String) {
self.store.insert(key, value);
}
/// Get a key's value.
/// Return Some(_) if the key exists, return None otherwise.
/// The return value is a copy of the stored value, so it won't delete the origin data.
///
/// # Example
///
/// ```
/// use kvs::KvStore;
/// let mut store = KvStore::new();
/// store.set("key".to_owned(), "value".to_owned());
/// assert_eq!(Some("value".to_owned()), store.get("key".to_owned()));
/// assert_eq!(None, store.get("kkkk".to_owned()));
/// ```
pub fn get(&self, key: String) -> Option<String> {
self.store.get(&key).cloned()
}
/// Remove a key's value
pub fn remove(&mut self, key: String) {
self.store.remove(&key);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.