<commit_before>use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{
    parse_quote, AngleBracketedGenericArguments, Attribute, Data, DeriveInput, Field, Fields,
    GenericArgument, GenericParam, Generics, ImplGenerics, ParenthesizedGenericArguments,
    PathArguments, Type, TypeGenerics, TypePath, TypeReference, TypeSlice, Variant,
};

enum StructKind {
    Struct,
    Tuple,
}

enum DataKind {
    Struct(Vec<Field>, StructKind),
    Enum(Vec<Variant>),
    Unit,
}

pub fn expand_derive_outgoing(input: DeriveInput) -> syn::Result<TokenStream> {
    let derive_deserialize = if no_deserialize_in_attrs(&input.attrs) {
        TokenStream::new()
    } else {
        quote!(::ruma_api::exports::serde::Deserialize)
    };

    let data = match input.data.clone() {
        Data::Union(_) => panic!("#[derive(Outgoing)] does not support Union types"),
        Data::Enum(e) => DataKind::Enum(e.variants.into_iter().collect()),
        Data::Struct(s) => match s.fields {
            Fields::Named(fs) => {
                DataKind::Struct(fs.named.into_iter().collect(), StructKind::Struct)
            }
            Fields::Unnamed(fs) => {
                DataKind::Struct(fs.unnamed.into_iter().collect(), StructKind::Tuple)
            }
            Fields::Unit => DataKind::Unit,
        },
    };

    match data {
        DataKind::Unit => Ok(impl_outgoing_with_incoming_self(&input)),
        DataKind::Enum(mut vars) => {
            let mut any_attribute = false;
            for var in &mut vars {
                for field in &mut var.fields {
                    if strip_lifetimes(&mut field.ty) {
                        any_attribute = true;
                    }
                }
            }

            let original_ident = &input.ident;
            let (original_impl_gen, original_ty_gen, _) = input.generics.split_for_impl();

            if !any_attribute {
                return Ok(impl_outgoing_with_incoming_self(&input));
            }

            let vis = input.vis;
            let doc = format!("'Incoming' variant of [{ty}](enum.{ty}.html).", ty = &input.ident);
            let incoming_ident =
                format_ident!("Incoming{}", original_ident, span = Span::call_site());
            let mut gen_copy = input.generics.clone();
            let (impl_gen, ty_gen) = split_for_impl_lifetime_less(&mut gen_copy);

            Ok(quote! {
                #[doc = #doc]
                #[derive(Debug, #derive_deserialize)]
                #vis enum #incoming_ident #ty_gen { #( #vars, )* }

                impl #original_impl_gen ::ruma_api::Outgoing for #original_ident #original_ty_gen {
                    type Incoming = #incoming_ident #impl_gen;
                }
            })
        }
        DataKind::Struct(mut fields, struct_kind) => {
            let mut any_attribute = false;
            for field in &mut fields {
                if strip_lifetimes(&mut field.ty) {
                    any_attribute = true;
                }
            }

            let original_ident = &input.ident;
            let (original_impl_gen, original_ty_gen, _) = input.generics.split_for_impl();

            if !any_attribute {
                return Ok(impl_outgoing_with_incoming_self(&input));
            }

            let vis = input.vis;
            let doc = format!("'Incoming' variant of [{ty}](struct.{ty}.html).", ty = &input.ident);
            let incoming_ident =
                format_ident!("Incoming{}", original_ident, span = Span::call_site());
            let mut gen_copy = input.generics.clone();
            let (impl_gen, ty_gen) = split_for_impl_lifetime_less(&mut gen_copy);

            let struct_def = match struct_kind {
                StructKind::Struct => quote! { { #(#fields,)* } },
                StructKind::Tuple => quote! { ( #(#fields,)* ); },
            };

            Ok(quote! {
                #[doc = #doc]
                #[derive(Debug, #derive_deserialize)]
                #vis struct #incoming_ident #ty_gen #struct_def

                impl #original_impl_gen ::ruma_api::Outgoing for #original_ident #original_ty_gen {
                    type Incoming = #incoming_ident #impl_gen;
                }
            })
        }
    }
}

fn no_deserialize_in_attrs(attrs: &[Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path.is_ident("incoming_no_deserialize"))
}

fn impl_outgoing_with_incoming_self(input: &DeriveInput) -> TokenStream {
    let ident = &input.ident;
    let (impl_gen, ty_gen, _) = input.generics.split_for_impl();
    quote! {
        impl #impl_gen ::ruma_api::Outgoing for #ident #ty_gen {
            type Incoming = Self;
        }
    }
}

fn split_for_impl_lifetime_less(generics: &mut Generics) -> (ImplGenerics, TypeGenerics) {
    generics.params = generics
        .params
        .clone()
        .into_iter()
        .filter(|param| !matches!(param, GenericParam::Lifetime(_)))
        .collect();

    let (impl_gen, ty_gen, _) = generics.split_for_impl();
    (impl_gen, ty_gen)
}

fn strip_lifetimes(field_type: &mut Type) -> bool {
    match field_type {
        // T<'a> -> IncomingT
        // The IncomingT has to be declared by the user of this derive macro.
        Type::Path(TypePath { path, .. }) => {
            let mut has_lifetimes = false;
            for seg in &mut path.segments {
                // strip generic lifetimes
                match &mut seg.arguments {
                    PathArguments::AngleBracketed(AngleBracketedGenericArguments {
                        args, ..
                    }) => {
                        *args = args
                            .clone()
                            .into_iter()
                            .map(|mut ty| {
                                if let GenericArgument::Type(ty) = &mut ty {
                                    strip_lifetimes(ty);
                                }
                                ty
                            })
                            .filter(|arg| {
                                if let GenericArgument::Lifetime(_) = arg {
                                    has_lifetimes = true;
                                    false
                                } else {
                                    true
                                }
                            })
                            .collect();
                    }
                    PathArguments::Parenthesized(ParenthesizedGenericArguments {
                        inputs, ..
                    }) => {
                        *inputs = inputs
                            .clone()
                            .into_iter()
                            .map(|mut ty| {
                                strip_lifetimes(&mut ty);
                                ty
                            })
                            .collect();
                    }
                    _ => {}
                }
            }

            if has_lifetimes {
                if let Some(name) = path.segments.last_mut() {
                    let incoming_ty_ident = format_ident!("Incoming{}", name.ident);
                    name.ident = incoming_ty_ident;
                }
            }

            has_lifetimes
        }
        Type::Reference(TypeReference { elem, .. }) => match &mut **elem {
            Type::Path(ty_path) => {
                let TypePath { path, .. } = ty_path;
                let segs = path
                    .segments
                    .clone()
                    .into_iter()
                    .map(|seg| seg.ident.to_string())
                    .collect::<Vec<_>>();

                if path.is_ident("str") {
                    // &str -> String
                    *field_type = parse_quote! { ::std::string::String };
                } else if segs.contains(&"DeviceId".into()) || segs.contains(&"ServerName".into()) {
                    // The identifiers that need to be boxed `Box<T>` since they are DST's.
                    *field_type = parse_quote! { ::std::boxed::Box<#path> };
                } else {
                    // &T -> T
                    *field_type = Type::Path(ty_path.clone());
                }
                true
            }
            // &[T] -> Vec<T>
            Type::Slice(TypeSlice { elem, .. }) => {
                // Recursively strip the lifetimes of the slice's elements.
                strip_lifetimes(&mut *elem);
                *field_type = parse_quote! { Vec<#elem> };
                true
            }
            _ => false,
        },
        _ => false,
    }
}
<commit_msg>Add tuple lifetime stripping to derive_outgoing<commit_after>use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{
    parse_quote, AngleBracketedGenericArguments, Attribute, Data, DeriveInput, Field, Fields,
    GenericArgument, GenericParam, Generics, ImplGenerics, ParenthesizedGenericArguments,
    PathArguments, Type, TypeGenerics, TypePath, TypeReference, TypeSlice, Variant,
};

enum StructKind {
    Struct,
    Tuple,
}

enum DataKind {
    Struct(Vec<Field>, StructKind),
    Enum(Vec<Variant>),
    Unit,
}

pub fn expand_derive_outgoing(input: DeriveInput) -> syn::Result<TokenStream> {
    let derive_deserialize = if no_deserialize_in_attrs(&input.attrs) {
        TokenStream::new()
    } else {
        quote!(::ruma_api::exports::serde::Deserialize)
    };

    let data = match input.data.clone() {
        Data::Union(_) => panic!("#[derive(Outgoing)] does not support Union types"),
        Data::Enum(e) => DataKind::Enum(e.variants.into_iter().collect()),
        Data::Struct(s) => match s.fields {
            Fields::Named(fs) => {
                DataKind::Struct(fs.named.into_iter().collect(), StructKind::Struct)
            }
            Fields::Unnamed(fs) => {
                DataKind::Struct(fs.unnamed.into_iter().collect(), StructKind::Tuple)
            }
            Fields::Unit => DataKind::Unit,
        },
    };

    match data {
        DataKind::Unit => Ok(impl_outgoing_with_incoming_self(&input)),
        DataKind::Enum(mut vars) => {
            let mut any_attribute = false;
            for var in &mut vars {
                for field in &mut var.fields {
                    if strip_lifetimes(&mut field.ty) {
                        any_attribute = true;
                    }
                }
            }

            let original_ident = &input.ident;
            let (original_impl_gen, original_ty_gen, _) = input.generics.split_for_impl();

            if !any_attribute {
                return Ok(impl_outgoing_with_incoming_self(&input));
            }

            let vis = input.vis;
            let doc = format!("'Incoming' variant of [{ty}](enum.{ty}.html).", ty = &input.ident);
            let incoming_ident =
                format_ident!("Incoming{}", original_ident, span = Span::call_site());
            let mut gen_copy = input.generics.clone();
            let (impl_gen, ty_gen) = split_for_impl_lifetime_less(&mut gen_copy);

            Ok(quote! {
                #[doc = #doc]
                #[derive(Debug, #derive_deserialize)]
                #vis enum #incoming_ident #ty_gen { #( #vars, )* }

                impl #original_impl_gen ::ruma_api::Outgoing for #original_ident #original_ty_gen {
                    type Incoming = #incoming_ident #impl_gen;
                }
            })
        }
        DataKind::Struct(mut fields, struct_kind) => {
            let mut any_attribute = false;
            for field in &mut fields {
                if strip_lifetimes(&mut field.ty) {
                    any_attribute = true;
                }
            }

            let original_ident = &input.ident;
            let (original_impl_gen, original_ty_gen, _) = input.generics.split_for_impl();

            if !any_attribute {
                return Ok(impl_outgoing_with_incoming_self(&input));
            }

            let vis = input.vis;
            let doc = format!("'Incoming' variant of [{ty}](struct.{ty}.html).", ty = &input.ident);
            let incoming_ident =
                format_ident!("Incoming{}", original_ident, span = Span::call_site());
            let mut gen_copy = input.generics.clone();
            let (impl_gen, ty_gen) = split_for_impl_lifetime_less(&mut gen_copy);

            let struct_def = match struct_kind {
                StructKind::Struct => quote! { { #(#fields,)* } },
                StructKind::Tuple => quote! { ( #(#fields,)* ); },
            };

            Ok(quote! {
                #[doc = #doc]
                #[derive(Debug, #derive_deserialize)]
                #vis struct #incoming_ident #ty_gen #struct_def

                impl #original_impl_gen ::ruma_api::Outgoing for #original_ident #original_ty_gen {
                    type Incoming = #incoming_ident #impl_gen;
                }
            })
        }
    }
}

fn no_deserialize_in_attrs(attrs: &[Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path.is_ident("incoming_no_deserialize"))
}

fn impl_outgoing_with_incoming_self(input: &DeriveInput) -> TokenStream {
    let ident = &input.ident;
    let (impl_gen, ty_gen, _) = input.generics.split_for_impl();
    quote! {
        impl #impl_gen ::ruma_api::Outgoing for #ident #ty_gen {
            type Incoming = Self;
        }
    }
}

fn split_for_impl_lifetime_less(generics: &mut Generics) -> (ImplGenerics, TypeGenerics) {
    generics.params = generics
        .params
        .clone()
        .into_iter()
        .filter(|param| !matches!(param, GenericParam::Lifetime(_)))
        .collect();

    let (impl_gen, ty_gen, _) = generics.split_for_impl();
    (impl_gen, ty_gen)
}

fn strip_lifetimes(field_type: &mut Type) -> bool {
    match field_type {
        // T<'a> -> IncomingT
        // The IncomingT has to be declared by the user of this derive macro.
        Type::Path(TypePath { path, .. }) => {
            let mut has_lifetimes = false;
            for seg in &mut path.segments {
                // strip generic lifetimes
                match &mut seg.arguments {
                    PathArguments::AngleBracketed(AngleBracketedGenericArguments {
                        args, ..
                    }) => {
                        *args = args
                            .clone()
                            .into_iter()
                            .map(|mut ty| {
                                if let GenericArgument::Type(ty) = &mut ty {
                                    strip_lifetimes(ty);
                                }
                                ty
                            })
                            .filter(|arg| {
                                if let GenericArgument::Lifetime(_) = arg {
                                    has_lifetimes = true;
                                    false
                                } else {
                                    true
                                }
                            })
                            .collect();
                    }
                    PathArguments::Parenthesized(ParenthesizedGenericArguments {
                        inputs, ..
                    }) => {
                        *inputs = inputs
                            .clone()
                            .into_iter()
                            .map(|mut ty| {
                                strip_lifetimes(&mut ty);
                                ty
                            })
                            .collect();
                    }
                    _ => {}
                }
            }

            if has_lifetimes {
                if let Some(name) = path.segments.last_mut() {
                    let incoming_ty_ident = format_ident!("Incoming{}", name.ident);
                    name.ident = incoming_ty_ident;
                }
            }

            has_lifetimes
        }
        Type::Reference(TypeReference { elem, .. }) => match &mut **elem {
            Type::Path(ty_path) => {
                let TypePath { path, .. } = ty_path;
                let segs = path
                    .segments
                    .clone()
                    .into_iter()
                    .map(|seg| seg.ident.to_string())
                    .collect::<Vec<_>>();

                if path.is_ident("str") {
                    // &str -> String
                    *field_type = parse_quote! { ::std::string::String };
                } else if segs.contains(&"DeviceId".into()) || segs.contains(&"ServerName".into()) {
                    // The identifiers that need to be boxed `Box<T>` since they are DST's.
                    *field_type = parse_quote! { ::std::boxed::Box<#path> };
                } else {
                    // &T -> T
                    *field_type = Type::Path(ty_path.clone());
                }
                true
            }
            // &[T] -> Vec<T>
            Type::Slice(TypeSlice { elem, .. }) => {
                // Recursively strip the lifetimes of the slice's elements.
                strip_lifetimes(&mut *elem);
                *field_type = parse_quote! { Vec<#elem> };
                true
            }
            _ => false,
        },
        Type::Tuple(syn::TypeTuple { elems, .. }) => {
            let mut has_lifetime = false;
            for elem in elems {
                if strip_lifetimes(elem) {
                    has_lifetime = true;
                }
            }
            has_lifetime
        }
        _ => false,
    }
}
<|endoftext|>


<commit_before>// Build the library.

extern crate gcc;

fn main() {
    let mut conf = gcc::Config::new();

    conf.file("../boot/bootutil/src/loader.c");
    conf.file("../boot/bootutil/src/bootutil_misc.c");
    conf.file("csupport/run.c");
    conf.include("../boot/bootutil/include");
    conf.include("../zephyr/include");
    conf.debug(true);
    conf.compile("libbootutil.a");
}
<commit_msg>sim: Add dependency output<commit_after>// Build the library.

extern crate gcc;

use std::fs;
use std::io;
use std::path::Path;

fn main() {
    let mut conf = gcc::Config::new();

    conf.file("../boot/bootutil/src/loader.c");
    conf.file("../boot/bootutil/src/bootutil_misc.c");
    conf.file("csupport/run.c");
    conf.include("../boot/bootutil/include");
    conf.include("../zephyr/include");
    conf.debug(true);
    conf.compile("libbootutil.a");
    walk_dir("../boot").unwrap();
    walk_dir("csupport").unwrap();
    walk_dir("../zephyr").unwrap();
}

// Output the names of all files within a directory so that Cargo knows when to rebuild.
fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
    for ent in fs::read_dir(path.as_ref())? {
        let ent = ent?;
        let p = ent.path();
        if p.is_dir() {
            walk_dir(p)?;
        } else {
            // Note that non-utf8 names will fail.
            let name = p.to_str().unwrap();
            if name.ends_with(".c") || name.ends_with(".h") {
                println!("cargo:rerun-if-changed={}", name);
            }
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before>//! Simple websocket client.

#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate futures;
extern crate tokio_core;

use std::{io, thread};
use std::time::Duration;

use actix::*;
use futures::Future;
use actix_web::ws::{Message, WsClientError, WsClient, WsClientWriter};

fn main() {
    ::std::env::set_var("RUST_LOG", "actix_web=info");
    let _ = env_logger::init();
    let sys = actix::System::new("ws-example");

    Arbiter::handle().spawn(
        WsClient::new("http://127.0.0.1:8080/ws/")
            .connect().unwrap()
            .map_err(|e| {
                println!("Error: {}", e);
                ()
            })
            .map(|(reader, writer)| {
                let addr: SyncAddress<_> = ChatClient::create(|ctx| {
                    ChatClient::add_stream(reader, ctx);
                    ChatClient(writer)
                });

                // start console loop
                thread::spawn(move|| {
                    loop {
                        let mut cmd = String::new();
                        if io::stdin().read_line(&mut cmd).is_err() {
                            println!("error");
                            return
                        }
                        addr.send(ClientCommand(cmd));
                    }
                });

                ()
            })
    );

    let _ = sys.run();
}

struct ChatClient(WsClientWriter);

#[derive(Message)]
struct ClientCommand(String);

impl Actor for ChatClient {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Context<Self>) {
        // start heartbeats otherwise server will disconnect after 10 seconds
        self.hb(ctx)
    }

    fn stopping(&mut self, _: &mut Context<Self>) -> bool {
        println!("Stopping");

        // Stop application on disconnect
        Arbiter::system().send(actix::msgs::SystemExit(0));

        true
    }
}

impl ChatClient {
    fn hb(&self, ctx: &mut Context<Self>) {
        ctx.run_later(Duration::new(1, 0), |act, ctx| {
            act.0.ping("");
            act.hb(ctx);
        });
    }
}

/// Handle stdin commands
impl Handler<ClientCommand> for ChatClient {
    type Result = ();

    fn handle(&mut self, msg: ClientCommand, ctx: &mut Context<Self>) {
        self.0.text(msg.0.as_str())
    }
}

/// Handle server websocket messages
impl StreamHandler<Message, WsClientError> for ChatClient {

    fn handle(&mut self, msg: Message, ctx: &mut Context<Self>) {
        match msg {
            Message::Text(txt) => println!("Server: {:?}", txt),
            _ => ()
        }
    }

    fn started(&mut self, ctx: &mut Context<Self>) {
        println!("Connected");
    }

    fn finished(&mut self, err: Option<WsClientError>, ctx: &mut Context<Self>) {
        println!("Server disconnected");
        ctx.stop()
    }
}
<commit_msg>fix websocket example<commit_after>//! Simple websocket client.

#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate futures;
extern crate tokio_core;

use std::{io, thread};
use std::time::Duration;

use actix::*;
use futures::Future;
use actix_web::ws::{Message, WsClientError, WsClient, WsClientWriter};

fn main() {
    ::std::env::set_var("RUST_LOG", "actix_web=info");
    let _ = env_logger::init();
    let sys = actix::System::new("ws-example");

    Arbiter::handle().spawn(
        WsClient::new("http://127.0.0.1:8080/ws/")
            .connect().unwrap()
            .map_err(|e| {
                println!("Error: {}", e);
                ()
            })
            .map(|(reader, writer)| {
                let addr: SyncAddress<_> = ChatClient::create(|ctx| {
                    ChatClient::add_stream(reader, ctx);
                    ChatClient(writer)
                });

                // start console loop
                thread::spawn(move|| {
                    loop {
                        let mut cmd = String::new();
                        if io::stdin().read_line(&mut cmd).is_err() {
                            println!("error");
                            return
                        }
                        addr.send(ClientCommand(cmd));
                    }
                });

                ()
            })
    );

    let _ = sys.run();
}

struct ChatClient(WsClientWriter);

#[derive(Message)]
struct ClientCommand(String);

impl Actor for ChatClient {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Context<Self>) {
        // start heartbeats otherwise server will disconnect after 10 seconds
        self.hb(ctx)
    }

    fn stopping(&mut self, _: &mut Context<Self>) -> bool {
        println!("Stopping");

        // Stop application on disconnect
        Arbiter::system().send(actix::msgs::SystemExit(0));

        true
    }
}

impl ChatClient {
    fn hb(&self, ctx: &mut Context<Self>) {
        ctx.run_later(Duration::new(1, 0), |act, ctx| {
            act.0.ping("");
            act.hb(ctx);
        });
    }
}

/// Handle stdin commands
impl Handler<ClientCommand> for ChatClient {
    type Result = ();

    fn handle(&mut self, msg: ClientCommand, ctx: &mut Context<Self>) {
        self.0.text(msg.0.as_str())
    }
}

/// Handle server websocket messages
impl StreamHandler<Message, WsClientError> for ChatClient {

    fn handle(&mut self, msg: Message, ctx: &mut Context<Self>) {
        match msg {
            Message::Text(txt) => println!("Server: {:?}", txt),
            _ => ()
        }
    }

    fn started(&mut self, ctx: &mut Context<Self>) {
        println!("Connected");
    }

    fn finished(&mut self, ctx: &mut Context<Self>) {
        println!("Server disconnected");
        ctx.stop()
    }
}
<|endoftext|>


<commit_before>use redox::*;
use super::*;
use core::iter::FromIterator;

#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
    /// Append text (after the cursor)
    Append,
    /// Insert text (before the cursor)
    Insert,
    /// Replace text (on the cursor)
    Replace,
}

#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
    /// The mode type
    pub mode: InsertMode,
}

impl Editor {
    /// Delta x, i.e. the cursors visual position's x coordinate relative to the cursors actual
    /// position. For example append will append character after the cursor, but visually it have
    /// delta x = 1, so it will look like normal insert mode, except when going back to normal
    /// mode, the cursor will move back (visually), because the delta x will drop to 0.
    pub fn delta(&self) -> usize {
        let (x, y) = self.pos();
        match self.cursor().mode {
            _ if x > self.text[y].len() => {
                0
            },
            Mode::Primitive(PrimitiveMode::Insert(InsertOptions { mode: InsertMode::Append })) if x == self.text[y].len() => 0,

            Mode::Primitive(PrimitiveMode::Insert(InsertOptions { mode: InsertMode::Append })) => 1,
            _ => 0,
        }
    }

    /// Insert text under the current cursor.
    pub fn insert(&mut self, k: Key, InsertOptions { mode: mode }: InsertOptions) {
        let (mut x, mut y) = self.pos();
        match mode {
            InsertMode::Insert | InsertMode::Append => {
                let d = self.delta();

                match k {
                    Key::Char('\n') => {
                        let ln = self.text[y].clone();
                        let (slice, _) = ln.as_slices();

                        let first_part = (&slice[..x + d]).clone();
                        let second_part = (&slice[x + d..]).clone();

                        self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));

                        let ind = if self.options.autoindent {
                            self.get_indent(y)
                        } else {
                            VecDeque::new()
                        };
                        let begin = ind.len();

                        self.text.insert(y + 1, VecDeque::from_iter(
                                ind.into_iter().chain(second_part.iter().map(|x| *x))
                        ));

                        self.redraw_task = RedrawTask::LinesAfter(y);
                        self.goto((begin, y + 1));
                    },
                    Key::Backspace => { // Backspace
                        let prev = self.previous(1);
                        if let Some((x, y)) = prev {
                            //if self.x() != 0 || self.y() != 0 {
                            self.goto((x + d, y));
                            self.delete();
                            //}
                        }
                    },
                    Key::Char(c) => {
                        self.text[y].insert(x + d, c);

                        // TODO: Are there a better way than switching?
                        match mode {
                            InsertMode::Insert if x + 1 == self.text[y].len() => {                                self.cursor_mut().mode = Mode::Primitive(PrimitiveMode::Insert(InsertOptions {
                                    mode: InsertMode::Append,
                                }));
                            },
                            _ => {},
                        }

                        self.redraw_task = RedrawTask::Lines(y..y + 1);
                        let right = self.right(1);
                        self.goto(right);
                    }
                    _ => {},
                }
            },
            InsertMode::Replace => match k {
                Key::Char(c) => {
                    if x == self.text[y].len() {
                        let next = self.next(1);
                        if let Some(p) = next {
                            self.goto(p);
                            x = self.x();
                            y = self.y();
                        }
                    }

                    if self.text.len() != y {
                        if self.text[y].len() == x {
                            let next = self.next(1);
                            if let Some(p) = next {
                                self.goto(p);
                            }
                        } else {
                            self.text[y][x] = c;
                        }
                    }
                    let next = self.next(1);
                    if let Some(p) = next {
                        self.goto(p);
                    }
                    self.redraw_task = RedrawTask::Lines(y..y + 1);
                },
                _ => {},
            },
        }
    }

    /// Insert a string
    pub fn insert_str(&mut self, txt: String, opt: InsertOptions) {
        for c in txt.chars() {
            self.insert(Key::Char(c), opt);
        }
    }

}
<commit_msg>Remove bug in backspace, when in insert mode<commit_after>use redox::*;
use super::*;
use core::iter::FromIterator;

#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
    /// Append text (after the cursor)
    Append,
    /// Insert text (before the cursor)
    Insert,
    /// Replace text (on the cursor)
    Replace,
}

#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
    /// The mode type
    pub mode: InsertMode,
}

impl Editor {
    /// Delta x, i.e. the cursors visual position's x coordinate relative to the cursors actual
    /// position. For example append will append character after the cursor, but visually it have
    /// delta x = 1, so it will look like normal insert mode, except when going back to normal
    /// mode, the cursor will move back (visually), because the delta x will drop to 0.
    pub fn delta(&self) -> usize {
        let (x, y) = self.pos();
        match self.cursor().mode {
            _ if x > self.text[y].len() => {
                0
            },
            Mode::Primitive(PrimitiveMode::Insert(InsertOptions { mode: InsertMode::Append })) if x == self.text[y].len() => 0,

            Mode::Primitive(PrimitiveMode::Insert(InsertOptions { mode: InsertMode::Append })) => 1,
            _ => 0,
        }
    }

    /// Insert text under the current cursor.
    pub fn insert(&mut self, k: Key, InsertOptions { mode: mode }: InsertOptions) {
        let (mut x, mut y) = self.pos();
        match mode {
            InsertMode::Insert | InsertMode::Append => {
                let d = self.delta();

                match k {
                    Key::Char('\n') => {
                        let ln = self.text[y].clone();
                        let (slice, _) = ln.as_slices();

                        let first_part = (&slice[..x + d]).clone();
                        let second_part = (&slice[x + d..]).clone();

                        self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));

                        let ind = if self.options.autoindent {
                            self.get_indent(y)
                        } else {
                            VecDeque::new()
                        };
                        let begin = ind.len();

                        self.text.insert(y + 1, VecDeque::from_iter(
                                ind.into_iter().chain(second_part.iter().map(|x| *x))
                        ));

                        self.redraw_task = RedrawTask::LinesAfter(y);
                        self.goto((begin, y + 1));
                    },
                    Key::Backspace => { // Backspace
                        let del = if self.text[y].len() == 0 {
                            1
                        } else if d == 0 && x == 0 {
                            self.cursor_mut().mode = Mode::Primitive(PrimitiveMode::Insert(InsertOptions { mode: InsertMode::Append }));
                            1

                        } else {
                            1 - d
                        };
                        let prev = self.previous(del);
                        if let Some((x, y)) = prev {
                            //if self.x() != 0 || self.y() != 0 {
                            self.goto((x + d, y));
                            self.delete();
                            //}
                        }
                    },
                    Key::Char(c) => {
                        self.text[y].insert(x + d, c);

                        // TODO: Are there a better way than switching?
                        match mode {
                            InsertMode::Insert if x + 1 == self.text[y].len() => {                                self.cursor_mut().mode = Mode::Primitive(PrimitiveMode::Insert(InsertOptions {
                                    mode: InsertMode::Append,
                                }));
                            },
                            _ => {},
                        }

                        self.redraw_task = RedrawTask::Lines(y..y + 1);
                        let right = self.right(1);
                        self.goto(right);
                    }
                    _ => {},
                }
            },
            InsertMode::Replace => match k {
                Key::Char(c) => {
                    if x == self.text[y].len() {
                        let next = self.next(1);
                        if let Some(p) = next {
                            self.goto(p);
                            x = self.x();
                            y = self.y();
                        }
                    }

                    if self.text.len() != y {
                        if self.text[y].len() == x {
                            let next = self.next(1);
                            if let Some(p) = next {
                                self.goto(p);
                            }
                        } else {
                            self.text[y][x] = c;
                        }
                    }
                    let next = self.next(1);
                    if let Some(p) = next {
                        self.goto(p);
                    }
                    self.redraw_task = RedrawTask::Lines(y..y + 1);
                },
                _ => {},
            },
        }
    }

    /// Insert a string
    pub fn insert_str(&mut self, txt: String, opt: InsertOptions) {
        for c in txt.chars() {
            self.insert(Key::Char(c), opt);
        }
    }

}
<|endoftext|>


<commit_before>//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.

use std::sync::atomic::{AtomicUsize, Ordering};

static HOOK_COUNT: AtomicUsize = AtomicUsize::new(0);

fn main() {
    // inspect the `PanicInfo` we receive to ensure the right file is the source
    std::panic::set_hook(Box::new(|info| {
        HOOK_COUNT.fetch_add(1, Ordering::Relaxed);
        let actual = info.location().unwrap();
        if actual.file() != file!() {
            eprintln!("expected a location in the test file, found {:?}", actual);
            panic!();
        }
    }));

    fn assert_panicked(f: impl FnOnce() + std::panic::UnwindSafe) {
        std::panic::catch_unwind(f).unwrap_err();
    }

    let nope: Option<()> = None;
    assert_panicked(|| nope.unwrap());
    assert_panicked(|| nope.expect(""));

    let oops: Result<(), ()> = Err(());
    assert_panicked(|| oops.unwrap());
    assert_panicked(|| oops.expect(""));

    let fine: Result<(), ()> = Ok(());
    assert_panicked(|| fine.unwrap_err());
    assert_panicked(|| fine.expect_err(""));

    // Cleanup: reset to default hook.
    drop(std::panic::take_hook());

    assert_eq!(HOOK_COUNT.load(Ordering::Relaxed), 8);
}
<commit_msg>Fix panic test.<commit_after>//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.

use std::sync::atomic::{AtomicUsize, Ordering};

static HOOK_COUNT: AtomicUsize = AtomicUsize::new(0);

fn main() {
    // inspect the `PanicInfo` we receive to ensure the right file is the source
    std::panic::set_hook(Box::new(|info| {
        HOOK_COUNT.fetch_add(1, Ordering::Relaxed);
        let actual = info.location().unwrap();
        if actual.file() != file!() {
            eprintln!("expected a location in the test file, found {:?}", actual);
            panic!();
        }
    }));

    fn assert_panicked(f: impl FnOnce() + std::panic::UnwindSafe) {
        std::panic::catch_unwind(f).unwrap_err();
    }

    let nope: Option<()> = None;
    assert_panicked(|| nope.unwrap());
    assert_panicked(|| nope.expect(""));

    let oops: Result<(), ()> = Err(());
    assert_panicked(|| oops.unwrap());
    assert_panicked(|| oops.expect(""));

    let fine: Result<(), ()> = Ok(());
    assert_panicked(|| fine.unwrap_err());
    assert_panicked(|| fine.expect_err(""));

    // Cleanup: reset to default hook.
    drop(std::panic::take_hook());

    assert_eq!(HOOK_COUNT.load(Ordering::Relaxed), 6);
}
<|endoftext|>


<commit_before>use fortanix_sgx_abi::Tcs;

use super::abi::thread;

use super::waitqueue::{try_lock_or_false, NotifiedTcs, SpinMutex, WaitQueue, WaitVariable};

pub struct Mutex {
    inner: SpinMutex<WaitVariable<bool>>,
}

pub type MovableMutex = Box<Mutex>;

// Implementation according to “Operating Systems: Three Easy Pieces”, chapter 28
impl Mutex {
    pub const fn new() -> Mutex {
        Mutex { inner: SpinMutex::new(WaitVariable::new(false)) }
    }

    #[inline]
    pub unsafe fn init(&mut self) {}

    #[inline]
    pub unsafe fn lock(&self) {
        let mut guard = self.inner.lock();
        if *guard.lock_var() {
            // Another thread has the lock, wait
            WaitQueue::wait(guard, || {})
        // Another thread has passed the lock to us
        } else {
            // We are just now obtaining the lock
            *guard.lock_var_mut() = true;
        }
    }

    #[inline]
    pub unsafe fn unlock(&self) {
        let guard = self.inner.lock();
        if let Err(mut guard) = WaitQueue::notify_one(guard) {
            // No other waiters, unlock
            *guard.lock_var_mut() = false;
        } else {
            // There was a thread waiting, just pass the lock
        }
    }

    #[inline]
    pub unsafe fn try_lock(&self) -> bool {
        let mut guard = try_lock_or_false!(self.inner);
        if *guard.lock_var() {
            // Another thread has the lock
            false
        } else {
            // We are just now obtaining the lock
            *guard.lock_var_mut() = true;
            true
        }
    }

    #[inline]
    pub unsafe fn destroy(&self) {}
}

struct ReentrantLock {
    owner: Option<Tcs>,
    count: usize,
}

pub struct ReentrantMutex {
    inner: SpinMutex<WaitVariable<ReentrantLock>>,
}

impl ReentrantMutex {
    pub const fn uninitialized() -> ReentrantMutex {
        ReentrantMutex {
            inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })),
        }
    }

    #[inline]
    pub unsafe fn init(&self) {}

    #[inline]
    pub unsafe fn lock(&self) {
        let mut guard = self.inner.lock();
        match guard.lock_var().owner {
            Some(tcs) if tcs != thread::current() => {
                // Another thread has the lock, wait
                WaitQueue::wait(guard, || {});
                // Another thread has passed the lock to us
            }
            _ => {
                // We are just now obtaining the lock
                guard.lock_var_mut().owner = Some(thread::current());
                guard.lock_var_mut().count += 1;
            }
        }
    }

    #[inline]
    pub unsafe fn unlock(&self) {
        let mut guard = self.inner.lock();
        if guard.lock_var().count > 1 {
            guard.lock_var_mut().count -= 1;
        } else {
            match WaitQueue::notify_one(guard) {
                Err(mut guard) => {
                    // No other waiters, unlock
                    guard.lock_var_mut().count = 0;
                    guard.lock_var_mut().owner = None;
                }
                Ok(mut guard) => {
                    // There was a thread waiting, just pass the lock
                    if let NotifiedTcs::Single(tcs) = guard.notified_tcs() {
                        guard.lock_var_mut().owner = Some(tcs)
                    } else {
                        unreachable!() // called notify_one
                    }
                }
            }
        }
    }

    #[inline]
    pub unsafe fn try_lock(&self) -> bool {
        let mut guard = try_lock_or_false!(self.inner);
        match guard.lock_var().owner {
            Some(tcs) if tcs != thread::current() => {
                // Another thread has the lock
                false
            }
            _ => {
                // We are just now obtaining the lock
                guard.lock_var_mut().owner = Some(thread::current());
                guard.lock_var_mut().count += 1;
                true
            }
        }
    }

    #[inline]
    pub unsafe fn destroy(&self) {}
}
<commit_msg>SGX mutex is movable<commit_after>use fortanix_sgx_abi::Tcs;

use super::abi::thread;

use super::waitqueue::{try_lock_or_false, NotifiedTcs, SpinMutex, WaitQueue, WaitVariable};

pub struct Mutex {
    inner: SpinMutex<WaitVariable<bool>>,
}

pub type MovableMutex = Mutex;

// Implementation according to “Operating Systems: Three Easy Pieces”, chapter 28
impl Mutex {
    pub const fn new() -> Mutex {
        Mutex { inner: SpinMutex::new(WaitVariable::new(false)) }
    }

    #[inline]
    pub unsafe fn init(&mut self) {}

    #[inline]
    pub unsafe fn lock(&self) {
        let mut guard = self.inner.lock();
        if *guard.lock_var() {
            // Another thread has the lock, wait
            WaitQueue::wait(guard, || {})
        // Another thread has passed the lock to us
        } else {
            // We are just now obtaining the lock
            *guard.lock_var_mut() = true;
        }
    }

    #[inline]
    pub unsafe fn unlock(&self) {
        let guard = self.inner.lock();
        if let Err(mut guard) = WaitQueue::notify_one(guard) {
            // No other waiters, unlock
            *guard.lock_var_mut() = false;
        } else {
            // There was a thread waiting, just pass the lock
        }
    }

    #[inline]
    pub unsafe fn try_lock(&self) -> bool {
        let mut guard = try_lock_or_false!(self.inner);
        if *guard.lock_var() {
            // Another thread has the lock
            false
        } else {
            // We are just now obtaining the lock
            *guard.lock_var_mut() = true;
            true
        }
    }

    #[inline]
    pub unsafe fn destroy(&self) {}
}

struct ReentrantLock {
    owner: Option<Tcs>,
    count: usize,
}

pub struct ReentrantMutex {
    inner: SpinMutex<WaitVariable<ReentrantLock>>,
}

impl ReentrantMutex {
    pub const fn uninitialized() -> ReentrantMutex {
        ReentrantMutex {
            inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })),
        }
    }

    #[inline]
    pub unsafe fn init(&self) {}

    #[inline]
    pub unsafe fn lock(&self) {
        let mut guard = self.inner.lock();
        match guard.lock_var().owner {
            Some(tcs) if tcs != thread::current() => {
                // Another thread has the lock, wait
                WaitQueue::wait(guard, || {});
                // Another thread has passed the lock to us
            }
            _ => {
                // We are just now obtaining the lock
                guard.lock_var_mut().owner = Some(thread::current());
                guard.lock_var_mut().count += 1;
            }
        }
    }

    #[inline]
    pub unsafe fn unlock(&self) {
        let mut guard = self.inner.lock();
        if guard.lock_var().count > 1 {
            guard.lock_var_mut().count -= 1;
        } else {
            match WaitQueue::notify_one(guard) {
                Err(mut guard) => {
                    // No other waiters, unlock
                    guard.lock_var_mut().count = 0;
                    guard.lock_var_mut().owner = None;
                }
                Ok(mut guard) => {
                    // There was a thread waiting, just pass the lock
                    if let NotifiedTcs::Single(tcs) = guard.notified_tcs() {
                        guard.lock_var_mut().owner = Some(tcs)
                    } else {
                        unreachable!() // called notify_one
                    }
                }
            }
        }
    }

    #[inline]
    pub unsafe fn try_lock(&self) -> bool {
        let mut guard = try_lock_or_false!(self.inner);
        match guard.lock_var().owner {
            Some(tcs) if tcs != thread::current() => {
                // Another thread has the lock
                false
            }
            _ => {
                // We are just now obtaining the lock
                guard.lock_var_mut().owner = Some(thread::current());
                guard.lock_var_mut().count += 1;
                true
            }
        }
    }

    #[inline]
    pub unsafe fn destroy(&self) {}
}
<|endoftext|>


<commit_before>fn read_string(a: String) -> Vec<u8> {
    a.bytes().collect()
}

fn fill_data(a: &mut Vec<u8>) {
    //fill data to N * 512 bits + 448 bits
    //N * 64 * 8 + 56 * 8
    let length = a.len();
    if (length % 8)
}

fn main() {
    let testcase0 = "test".to_string();
}
<commit_msg>a bit<commit_after>#![feature(exclusive_range_pattern)]
fn read_string(a: String) -> Vec<u8> {
    a.bytes().collect()
}

fn fill_data(a: &mut Vec<u8>) {
    //fill data to N * 512 bits + 448 bits
    //N * 64 * 8 + 56 * 8
    let length = a.len();
    let module = length % 64;
    match module {
        0..56 => {
            a.push(0b1000_0000u8);
            let left_bytes = 55 - module;
            for _ in 0..left_bytes {
                a.push(0b0000_0000u8)
            }
        }
        57..=63 => {
            a.push(0b1000_0000u8);
            let left_bytes = 63 - module + 56;
            for _ in 0..left_bytes {
                a.push(0b0000_0000u8)
            }
        }
        _ => {}
    }

    //then give length of this data
    let mut add_length = ((length * 8) as u64).to_be_bytes().to_vec();
    a.append(&mut add_length);
}

fn main() {
    // let mut a = vec![0b1011_0000u8];
    // fill_data(&mut a);
    // println!("{:?}", a.len());

    let mut b = [0b1001_1001u8; 67].to_vec();
    fill_data(&mut b);
    println!("{:?}", b);

    //println!("{:?}", (1 as u64).to_be_bytes());

    //let testcase0 = "test".to_string();
}
<|endoftext|>


<commit_before>//! Predicate functions for testing instruction fields.
//!
//! This module defines functions that are used by the instruction predicates defined by
//! `cranelift-codegen/meta/src/cdsl/instructions.rs` classes.
//!
//! The predicates the operate on integer fields use `Into<i64>` as a shared trait bound. This
//! bound is implemented by all the native integer types as well as `Imm64`.
//!
//! Some of these predicates may be unused in certain ISA configurations, so we suppress the
//! dead code warning.

use crate::ir;
use crate::ir::ConstantData;

/// Check that an integer value is zero.
#[allow(dead_code)]
pub fn is_zero_int<T: Into<i64>>(x: T) -> bool {
    x.into() == 0
}

/// Check that a 64-bit floating point value is zero.
#[allow(dead_code)]
pub fn is_zero_64_bit_float<T: Into<ir::immediates::Ieee64>>(x: T) -> bool {
    let x64 = x.into();
    x64.bits() == 0
}

/// Check that a 32-bit floating point value is zero.
#[allow(dead_code)]
pub fn is_zero_32_bit_float<T: Into<ir::immediates::Ieee32>>(x: T) -> bool {
    let x32 = x.into();
    x32.bits() == 0
}

/// Check that a 128-bit vector contains all zeroes.
#[allow(dead_code)]
pub fn is_all_zeroes(x: &ConstantData) -> bool {
    x.iter().all(|&f| f == 0)
}

/// Check that a 128-bit vector contains all ones.
#[allow(dead_code)]
pub fn is_all_ones(x: &ConstantData) -> bool {
    x.iter().all(|&f| f == 0xff)
}

/// Check that `x` is the same as `y`.
#[allow(dead_code)]
pub fn is_equal<T: Eq + Copy, O: Into<T> + Copy>(x: T, y: O) -> bool {
    x == y.into()
}

/// Check that `x` can be represented as a `wd`-bit signed integer with `sc` low zero bits.
#[allow(dead_code)]
pub fn is_signed_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {
    let s = x.into();
    s == (s >> sc << (64 - wd + sc) >> (64 - wd))
}

/// Check that `x` can be represented as a `wd`-bit unsigned integer with `sc` low zero bits.
#[allow(dead_code)]
pub fn is_unsigned_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {
    let u = x.into() as u64;
    // Bit-mask of the permitted bits.
    let m = (1 << wd) - (1 << sc);
    u == (u & m)
}

#[allow(dead_code)]
pub fn is_colocated_func(func_ref: ir::FuncRef, func: &ir::Function) -> bool {
    func.dfg.ext_funcs[func_ref].colocated
}

#[allow(dead_code)]
pub fn is_colocated_data(global_value: ir::GlobalValue, func: &ir::Function) -> bool {
    match func.global_values[global_value] {
        ir::GlobalValueData::Symbol { colocated, .. } => colocated,
        _ => panic!("is_colocated_data only makes sense for data with symbolic addresses"),
    }
}

#[allow(dead_code)]
pub fn has_length_of(value_list: &ir::ValueList, num: usize, func: &ir::Function) -> bool {
    value_list.len(&func.dfg.value_lists) == num
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cvt_u32() {
        let x1 = 0u32;
        let x2 = 1u32;
        let x3 = 0xffff_fff0u32;

        assert!(is_signed_int(x1, 1, 0));
        assert!(is_signed_int(x1, 2, 1));
        assert!(is_signed_int(x2, 2, 0));
        assert!(!is_signed_int(x2, 2, 1));

        // `u32` doesn't sign-extend when converted to `i64`.
        assert!(!is_signed_int(x3, 8, 0));

        assert!(is_unsigned_int(x1, 1, 0));
        assert!(is_unsigned_int(x1, 8, 4));
        assert!(is_unsigned_int(x2, 1, 0));
        assert!(!is_unsigned_int(x2, 8, 4));
        assert!(!is_unsigned_int(x3, 1, 0));
        assert!(is_unsigned_int(x3, 32, 4));
    }

    #[test]
    fn cvt_imm64() {
        use crate::ir::immediates::Imm64;

        let x1 = Imm64::new(-8);
        let x2 = Imm64::new(8);

        assert!(is_signed_int(x1, 16, 2));
        assert!(is_signed_int(x2, 16, 2));
        assert!(!is_signed_int(x1, 16, 4));
        assert!(!is_signed_int(x2, 16, 4));
    }

    #[test]
    fn check_is_all_zeroes() {
        assert!(is_all_zeroes(&[0; 16].as_ref().into()));
        assert!(is_all_zeroes(
            &vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].into()
        ));
        assert!(!is_all_zeroes(&[1; 16].as_ref().into()));
    }

    #[test]
    fn check_is_all_ones() {
        assert!(!is_all_ones(&[0; 16].as_ref().into()));
        assert!(is_all_ones(&[0xff; 16].as_ref().into()));
    }
}
<commit_msg>Update predicate documentation to match new ConstantData parameter<commit_after>//! Predicate functions for testing instruction fields.
//!
//! This module defines functions that are used by the instruction predicates defined by
//! `cranelift-codegen/meta/src/cdsl/instructions.rs` classes.
//!
//! The predicates the operate on integer fields use `Into<i64>` as a shared trait bound. This
//! bound is implemented by all the native integer types as well as `Imm64`.
//!
//! Some of these predicates may be unused in certain ISA configurations, so we suppress the
//! dead code warning.

use crate::ir;
use crate::ir::ConstantData;

/// Check that an integer value is zero.
#[allow(dead_code)]
pub fn is_zero_int<T: Into<i64>>(x: T) -> bool {
    x.into() == 0
}

/// Check that a 64-bit floating point value is zero.
#[allow(dead_code)]
pub fn is_zero_64_bit_float<T: Into<ir::immediates::Ieee64>>(x: T) -> bool {
    let x64 = x.into();
    x64.bits() == 0
}

/// Check that a 32-bit floating point value is zero.
#[allow(dead_code)]
pub fn is_zero_32_bit_float<T: Into<ir::immediates::Ieee32>>(x: T) -> bool {
    let x32 = x.into();
    x32.bits() == 0
}

/// Check that a constant contains all zeroes.
#[allow(dead_code)]
pub fn is_all_zeroes(x: &ConstantData) -> bool {
    x.iter().all(|&f| f == 0)
}

/// Check that a constant contains all ones.
#[allow(dead_code)]
pub fn is_all_ones(x: &ConstantData) -> bool {
    x.iter().all(|&f| f == 0xff)
}

/// Check that `x` is the same as `y`.
#[allow(dead_code)]
pub fn is_equal<T: Eq + Copy, O: Into<T> + Copy>(x: T, y: O) -> bool {
    x == y.into()
}

/// Check that `x` can be represented as a `wd`-bit signed integer with `sc` low zero bits.
#[allow(dead_code)]
pub fn is_signed_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {
    let s = x.into();
    s == (s >> sc << (64 - wd + sc) >> (64 - wd))
}

/// Check that `x` can be represented as a `wd`-bit unsigned integer with `sc` low zero bits.
#[allow(dead_code)]
pub fn is_unsigned_int<T: Into<i64>>(x: T, wd: u8, sc: u8) -> bool {
    let u = x.into() as u64;
    // Bit-mask of the permitted bits.
    let m = (1 << wd) - (1 << sc);
    u == (u & m)
}

#[allow(dead_code)]
pub fn is_colocated_func(func_ref: ir::FuncRef, func: &ir::Function) -> bool {
    func.dfg.ext_funcs[func_ref].colocated
}

#[allow(dead_code)]
pub fn is_colocated_data(global_value: ir::GlobalValue, func: &ir::Function) -> bool {
    match func.global_values[global_value] {
        ir::GlobalValueData::Symbol { colocated, .. } => colocated,
        _ => panic!("is_colocated_data only makes sense for data with symbolic addresses"),
    }
}

#[allow(dead_code)]
pub fn has_length_of(value_list: &ir::ValueList, num: usize, func: &ir::Function) -> bool {
    value_list.len(&func.dfg.value_lists) == num
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cvt_u32() {
        let x1 = 0u32;
        let x2 = 1u32;
        let x3 = 0xffff_fff0u32;

        assert!(is_signed_int(x1, 1, 0));
        assert!(is_signed_int(x1, 2, 1));
        assert!(is_signed_int(x2, 2, 0));
        assert!(!is_signed_int(x2, 2, 1));

        // `u32` doesn't sign-extend when converted to `i64`.
        assert!(!is_signed_int(x3, 8, 0));

        assert!(is_unsigned_int(x1, 1, 0));
        assert!(is_unsigned_int(x1, 8, 4));
        assert!(is_unsigned_int(x2, 1, 0));
        assert!(!is_unsigned_int(x2, 8, 4));
        assert!(!is_unsigned_int(x3, 1, 0));
        assert!(is_unsigned_int(x3, 32, 4));
    }

    #[test]
    fn cvt_imm64() {
        use crate::ir::immediates::Imm64;

        let x1 = Imm64::new(-8);
        let x2 = Imm64::new(8);

        assert!(is_signed_int(x1, 16, 2));
        assert!(is_signed_int(x2, 16, 2));
        assert!(!is_signed_int(x1, 16, 4));
        assert!(!is_signed_int(x2, 16, 4));
    }

    #[test]
    fn check_is_all_zeroes() {
        assert!(is_all_zeroes(&[0; 16].as_ref().into()));
        assert!(is_all_zeroes(
            &vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].into()
        ));
        assert!(!is_all_zeroes(&[1; 16].as_ref().into()));
    }

    #[test]
    fn check_is_all_ones() {
        assert!(!is_all_ones(&[0; 16].as_ref().into()));
        assert!(is_all_ones(&[0xff; 16].as_ref().into()));
    }
}
<|endoftext|>


<commit_before>// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::{
    common::{check_network, handle_request, with_context, with_empty_request},
    error::ApiError,
    types::{
        Allow, MetadataRequest, NetworkListResponse, NetworkOptionsResponse, NetworkRequest,
        NetworkStatusResponse, OperationStatusType, OperationType, Version,
    },
    RosettaContext, NODE_VERSION, ROSETTA_VERSION,
};
use aptos_logger::{debug, trace};
use warp::Filter;

pub fn list_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "list")
        .and(warp::post())
        .and(with_empty_request())
        .and(with_context(server_context))
        .and_then(handle_request(network_list))
}

pub fn options_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "options")
        .and(warp::post())
        .and(warp::body::json())
        .and(with_context(server_context))
        .and_then(handle_request(network_options))
}

pub fn status_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "status")
        .and(warp::post())
        .and(warp::body::json())
        .and(with_context(server_context))
        .and_then(handle_request(network_status))
}

/// List [`NetworkIdentifier`]s supported by this proxy aka [`ChainId`]s
///
/// This should be able to run without a running full node connection
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networklist)
async fn network_list(
    _empty: MetadataRequest,
    server_context: RosettaContext,
) -> Result<NetworkListResponse, ApiError> {
    debug!("/network/list");
    trace!(
        server_context = ?server_context,
        "network_list",
    );

    let response = NetworkListResponse {
        network_identifiers: vec![server_context.chain_id.into()],
    };

    Ok(response)
}

/// Get Network options
///
/// This lists out all errors, operations, and statuses, along with versioning information.
/// This should be able to run without a running full node connection
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networkoptions)
async fn network_options(
    request: NetworkRequest,
    server_context: RosettaContext,
) -> Result<NetworkOptionsResponse, ApiError> {
    debug!("/network/options");
    trace!(
        request = ?request,
        server_context = ?server_context,
        "network_options",
    );

    check_network(request.network_identifier, &server_context)?;

    let version = Version {
        rosetta_version: ROSETTA_VERSION.to_string(),
        // TODO: Get from node via REST API
        node_version: NODE_VERSION.to_string(),
        middleware_version: "0.1.0".to_string(),
    };

    let operation_statuses = OperationStatusType::all()
        .into_iter()
        .map(|status| status.into())
        .collect();
    let operation_types = OperationType::all()
        .into_iter()
        .map(|op| op.to_string())
        .collect();
    let errors = ApiError::all()
        .into_iter()
        .map(|err| err.into_error())
        .collect();

    let allow = Allow {
        operation_statuses,
        operation_types,
        errors,
        historical_balance_lookup: true,
        timestamp_start_index: 1,
        call_methods: vec![],
        balance_exemptions: vec![],
        mempool_coins: false,
    };

    let response = NetworkOptionsResponse { version, allow };

    Ok(response)
}

/// Get network status including the latest state
///
/// This should respond with the latest ledger version, timestamp, and genesis information
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networkoptions)
async fn network_status(
    request: NetworkRequest,
    server_context: RosettaContext,
) -> Result<NetworkStatusResponse, ApiError> {
    debug!("/network/status");
    trace!(
        request = ?request,
        server_context = ?server_context,
        "network_status",
    );

    check_network(request.network_identifier, &server_context)?;
    let chain_id = server_context.chain_id;
    let rest_client = server_context.rest_client()?;
    let block_cache = server_context.block_cache()?;
    let genesis_block_identifier = block_cache
        .get_block_info_by_height(0, chain_id)
        .await?
        .block_id;
    let response = rest_client.get_ledger_information().await?;
    let state = response.state();

    // Get the oldest block
    let oldest_block_identifier = block_cache
        .get_block_info_by_height(state.oldest_block_height, chain_id)
        .await?
        .block_id;

    // Get the latest block
    let current_block = block_cache
        .get_block_info_by_height(state.block_height, chain_id)
        .await?;
    let current_block_identifier = current_block.block_id;

    let response = NetworkStatusResponse {
        current_block_identifier,
        current_block_timestamp: current_block.timestamp,
        genesis_block_identifier,
        oldest_block_identifier,
        sync_status: None,
        peers: vec![],
    };

    Ok(response)
}
<commit_msg>[aptos-rosetta] Fix timestamp start index to 2<commit_after>// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::{
    common::{check_network, handle_request, with_context, with_empty_request},
    error::ApiError,
    types::{
        Allow, MetadataRequest, NetworkListResponse, NetworkOptionsResponse, NetworkRequest,
        NetworkStatusResponse, OperationStatusType, OperationType, Version,
    },
    RosettaContext, NODE_VERSION, ROSETTA_VERSION,
};
use aptos_logger::{debug, trace};
use warp::Filter;

pub fn list_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "list")
        .and(warp::post())
        .and(with_empty_request())
        .and(with_context(server_context))
        .and_then(handle_request(network_list))
}

pub fn options_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "options")
        .and(warp::post())
        .and(warp::body::json())
        .and(with_context(server_context))
        .and_then(handle_request(network_options))
}

pub fn status_route(
    server_context: RosettaContext,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path!("network" / "status")
        .and(warp::post())
        .and(warp::body::json())
        .and(with_context(server_context))
        .and_then(handle_request(network_status))
}

/// List [`NetworkIdentifier`]s supported by this proxy aka [`ChainId`]s
///
/// This should be able to run without a running full node connection
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networklist)
async fn network_list(
    _empty: MetadataRequest,
    server_context: RosettaContext,
) -> Result<NetworkListResponse, ApiError> {
    debug!("/network/list");
    trace!(
        server_context = ?server_context,
        "network_list",
    );

    let response = NetworkListResponse {
        network_identifiers: vec![server_context.chain_id.into()],
    };

    Ok(response)
}

/// Get Network options
///
/// This lists out all errors, operations, and statuses, along with versioning information.
/// This should be able to run without a running full node connection
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networkoptions)
async fn network_options(
    request: NetworkRequest,
    server_context: RosettaContext,
) -> Result<NetworkOptionsResponse, ApiError> {
    debug!("/network/options");
    trace!(
        request = ?request,
        server_context = ?server_context,
        "network_options",
    );

    check_network(request.network_identifier, &server_context)?;

    let version = Version {
        rosetta_version: ROSETTA_VERSION.to_string(),
        // TODO: Get from node via REST API
        node_version: NODE_VERSION.to_string(),
        middleware_version: "0.1.0".to_string(),
    };

    let operation_statuses = OperationStatusType::all()
        .into_iter()
        .map(|status| status.into())
        .collect();
    let operation_types = OperationType::all()
        .into_iter()
        .map(|op| op.to_string())
        .collect();
    let errors = ApiError::all()
        .into_iter()
        .map(|err| err.into_error())
        .collect();

    let allow = Allow {
        operation_statuses,
        operation_types,
        errors,
        historical_balance_lookup: true,
        timestamp_start_index: 2,
        call_methods: vec![],
        balance_exemptions: vec![],
        mempool_coins: false,
    };

    let response = NetworkOptionsResponse { version, allow };

    Ok(response)
}

/// Get network status including the latest state
///
/// This should respond with the latest ledger version, timestamp, and genesis information
///
/// [API Spec](https://www.rosetta-api.org/docs/NetworkApi.html#networkoptions)
async fn network_status(
    request: NetworkRequest,
    server_context: RosettaContext,
) -> Result<NetworkStatusResponse, ApiError> {
    debug!("/network/status");
    trace!(
        request = ?request,
        server_context = ?server_context,
        "network_status",
    );

    check_network(request.network_identifier, &server_context)?;
    let chain_id = server_context.chain_id;
    let rest_client = server_context.rest_client()?;
    let block_cache = server_context.block_cache()?;
    let genesis_block_identifier = block_cache
        .get_block_info_by_height(0, chain_id)
        .await?
        .block_id;
    let response = rest_client.get_ledger_information().await?;
    let state = response.state();

    // Get the oldest block
    let oldest_block_identifier = block_cache
        .get_block_info_by_height(state.oldest_block_height, chain_id)
        .await?
        .block_id;

    // Get the latest block
    let current_block = block_cache
        .get_block_info_by_height(state.block_height, chain_id)
        .await?;
    let current_block_identifier = current_block.block_id;

    let response = NetworkStatusResponse {
        current_block_identifier,
        current_block_timestamp: current_block.timestamp,
        genesis_block_identifier,
        oldest_block_identifier,
        sync_status: None,
        peers: vec![],
    };

    Ok(response)
}
<|endoftext|>


<commit_before>// Copyright 2022 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#[cfg(test)]
mod test {
    use crate::{Executor, TimerAsync};
    use std::time::{Duration, Instant};

    #[test]
    fn timer() {
        async fn this_test(ex: &Executor) {
            // On Windows, SetWaitableTimer, the underlying timer API, is not
            // guaranteed to sleep for *at least* the supplied duration, so here
            // we permit early wakeups.
            let dur = Duration::from_millis(200);
            let min_duration = Duration::from_millis(190);

            let now = Instant::now();
            TimerAsync::sleep(ex, dur).await.expect("unable to sleep");
            let actual_sleep_duration = now.elapsed();
            assert!(actual_sleep_duration >= min_duration);
        }

        let ex = Executor::new().expect("creating an executor failed");
        ex.run_until(this_test(&ex)).unwrap();
    }
}
<commit_msg>cros_async: Fix windows timer flake<commit_after>// Copyright 2022 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#[cfg(test)]
mod test {
    use crate::{Executor, TimerAsync};
    use std::time::{Duration, Instant};

    #[test]
    fn timer() {
        async fn this_test(ex: &Executor) {
            // On Windows, SetWaitableTimer, the underlying timer API, is not
            // guaranteed to sleep for *at least* the supplied duration, so here
            // we permit early wakeups.
            let dur = Duration::from_millis(200);
            let min_duration = Duration::from_millis(150);

            let now = Instant::now();
            TimerAsync::sleep(ex, dur).await.expect("unable to sleep");
            let actual_sleep_duration = now.elapsed();
            assert!(actual_sleep_duration >= min_duration);
        }

        let ex = Executor::new().expect("creating an executor failed");
        ex.run_until(this_test(&ex)).unwrap();
    }
}
<|endoftext|>


<commit_before>use crate::direction::Direction;
use crate::event::{AnyCb, Event, EventResult};
use crate::rect::Rect;
use crate::view::{AnyView, Selector};
use crate::Printer;
use crate::Vec2;
use std::any::Any;

/// Main trait defining a view behaviour.
///
/// This is what you should implement to define a custom View.
pub trait View: Any + AnyView {
    /// Draws the view with the given printer (includes bounds) and focus.
    ///
    /// This is the only *required* method to implement.
    fn draw(&self, printer: &Printer<'_, '_>);

    /// Called once the size for this view has been decided.
    ///
    /// It can be used to pre-compute the configuration of child views.
    ///
    /// View groups should propagate the information to their children.
    ///
    /// At this point, the given size is final and cannot be negociated.
    /// It is guaranteed to be the size available for the call to `draw()`.
    fn layout(&mut self, _: Vec2) {}

    /// Should return `true` if the view content changed since the last call
    /// to `layout()`.
    ///
    /// This is mostly an optimisation for views where the layout phase is
    /// expensive.
    ///
    /// * Views can ignore it and always return true (default implementation).
    ///   They will always be assumed to have changed.
    /// * View Groups can ignore it and always re-layout their children.
    ///     * If they call `required_size` or `layout` with stable parameters,
    ///       the children may cache the result themselves and speed up the
    ///       process anyway.
    fn needs_relayout(&self) -> bool {
        true
    }

    /// Returns the minimum size the view requires with the given restrictions.
    ///
    /// This is the main way a view communicate its size to its parent.
    ///
    /// Some views have a fixed size, and will ignore the `constraint`
    /// parameter entirely.
    ///
    /// Some views are flexible, and may adapt fully or partially to the
    /// constraints.
    ///
    /// Default implementation always return `(1,1)`.
    fn required_size(&mut self, constraint: Vec2) -> Vec2 {
        let _ = constraint;
        Vec2::new(1, 1)
    }

    /// Called when an event is received (key press, mouse event, ...).
    ///
    /// You can return an `EventResult`:
    /// * `EventResult::Ignored` means the event was not processed and may be
    ///    sent to another view.
    /// * `EventResult::Consumed` means the event was consumed and should not
    ///    be sent to any other view. It may in addition include a callback
    ///    to be run.
    ///
    /// The default implementation just ignores any event.
    fn on_event(&mut self, _: Event) -> EventResult {
        EventResult::Ignored
    }

    /// Runs a closure on the view identified by the given selector.
    ///
    /// See [`Finder::call_on`] for a nicer interface, implemented for all
    /// views.
    ///
    /// [`Finder::call_on`]: crate::view::Finder::call_on
    ///
    /// If the selector doesn't find a match, the closure will not be run.
    ///
    /// View groups should implement this to forward the call to each children.
    ///
    /// Default implementation is a no-op.
    fn call_on_any<'a>(&mut self, _: &Selector<'_>, _: AnyCb<'a>) {
        // TODO: FnMut -> FnOnce once it works
    }

    /// Moves the focus to the view identified by the given selector.
    ///
    /// Returns `Ok(())` if the view was found and selected.
    ///
    /// Default implementation simply returns `Err(())`.
    fn focus_view(&mut self, _: &Selector<'_>) -> Result<(), ()> {
        Err(())
    }

    /// This view is offered focus. Will it take it?
    ///
    /// `source` indicates where the focus comes from.
    /// When the source is unclear, `Front` is usually used.
    ///
    /// Default implementation always return `false`.
    fn take_focus(&mut self, source: Direction) -> bool {
        let _ = source;
        false
    }

    /// What part of the view is important and should be visible?
    ///
    /// When only part of this view can be visible, this helps
    /// determine which part.
    ///
    /// It is given the view size (same size given to `layout`).
    ///
    /// Default implementation return the entire view.
    fn important_area(&self, view_size: Vec2) -> Rect {
        Rect::from_size((0, 0), view_size)
    }

    /// Returns the type of this view.
    ///
    /// Useful when you have a `&dyn View`.
    fn type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

impl dyn View {
    /// Attempts to downcast `self` to a concrete type.
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.as_any().downcast_ref()
    }

    /// Attempts to downcast `self` to a concrete type.
    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
        self.as_any_mut().downcast_mut()
    }

    /// Attempts to downcast `Box<Self>` to a concrete type.
    pub fn downcast<T: Any>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
        // Do the check here + unwrap, so the error
        // value is `Self` and not `dyn Any`.
        if self.as_any().is::<T>() {
            Ok(self.as_boxed_any().downcast().unwrap())
        } else {
            Err(self)
        }
    }

    /// Checks if this view is of type `T`.
    pub fn is<T: Any>(&self) -> bool {
        self.as_any().is::<T>()
    }
}
<commit_msg>Mention Direction::None in View::take_focus<commit_after>use crate::direction::Direction;
use crate::event::{AnyCb, Event, EventResult};
use crate::rect::Rect;
use crate::view::{AnyView, Selector};
use crate::Printer;
use crate::Vec2;
use std::any::Any;

/// Main trait defining a view behaviour.
///
/// This is what you should implement to define a custom View.
pub trait View: Any + AnyView {
    /// Draws the view with the given printer (includes bounds) and focus.
    ///
    /// This is the only *required* method to implement.
    fn draw(&self, printer: &Printer<'_, '_>);

    /// Called once the size for this view has been decided.
    ///
    /// It can be used to pre-compute the configuration of child views.
    ///
    /// View groups should propagate the information to their children.
    ///
    /// At this point, the given size is final and cannot be negociated.
    /// It is guaranteed to be the size available for the call to `draw()`.
    fn layout(&mut self, _: Vec2) {}

    /// Should return `true` if the view content changed since the last call
    /// to `layout()`.
    ///
    /// This is mostly an optimisation for views where the layout phase is
    /// expensive.
    ///
    /// * Views can ignore it and always return true (default implementation).
    ///   They will always be assumed to have changed.
    /// * View Groups can ignore it and always re-layout their children.
    ///     * If they call `required_size` or `layout` with stable parameters,
    ///       the children may cache the result themselves and speed up the
    ///       process anyway.
    fn needs_relayout(&self) -> bool {
        true
    }

    /// Returns the minimum size the view requires with the given restrictions.
    ///
    /// This is the main way a view communicate its size to its parent.
    ///
    /// Some views have a fixed size, and will ignore the `constraint`
    /// parameter entirely.
    ///
    /// Some views are flexible, and may adapt fully or partially to the
    /// constraints.
    ///
    /// Default implementation always return `(1,1)`.
    fn required_size(&mut self, constraint: Vec2) -> Vec2 {
        let _ = constraint;
        Vec2::new(1, 1)
    }

    /// Called when an event is received (key press, mouse event, ...).
    ///
    /// You can return an `EventResult`:
    /// * `EventResult::Ignored` means the event was not processed and may be
    ///    sent to another view.
    /// * `EventResult::Consumed` means the event was consumed and should not
    ///    be sent to any other view. It may in addition include a callback
    ///    to be run.
    ///
    /// The default implementation just ignores any event.
    fn on_event(&mut self, _: Event) -> EventResult {
        EventResult::Ignored
    }

    /// Runs a closure on the view identified by the given selector.
    ///
    /// See [`Finder::call_on`] for a nicer interface, implemented for all
    /// views.
    ///
    /// [`Finder::call_on`]: crate::view::Finder::call_on
    ///
    /// If the selector doesn't find a match, the closure will not be run.
    ///
    /// View groups should implement this to forward the call to each children.
    ///
    /// Default implementation is a no-op.
    fn call_on_any<'a>(&mut self, _: &Selector<'_>, _: AnyCb<'a>) {
        // TODO: FnMut -> FnOnce once it works
    }

    /// Moves the focus to the view identified by the given selector.
    ///
    /// Returns `Ok(())` if the view was found and selected.
    ///
    /// Default implementation simply returns `Err(())`.
    fn focus_view(&mut self, _: &Selector<'_>) -> Result<(), ()> {
        Err(())
    }

    /// This view is offered focus. Will it take it?
    ///
    /// `source` indicates where the focus comes from.
    /// When the source is unclear, `Front` is usually used.
    ///
    /// Default implementation always return `false`.
    ///
    /// If the source is `Direction::Abs(Absolute::None)`, it is _recommended_
    /// not to change the current focus selection.
    fn take_focus(&mut self, source: Direction) -> bool {
        let _ = source;
        false
    }

    /// What part of the view is important and should be visible?
    ///
    /// When only part of this view can be visible, this helps
    /// determine which part.
    ///
    /// It is given the view size (same size given to `layout`).
    ///
    /// Default implementation return the entire view.
    fn important_area(&self, view_size: Vec2) -> Rect {
        Rect::from_size((0, 0), view_size)
    }

    /// Returns the type of this view.
    ///
    /// Useful when you have a `&dyn View`.
    fn type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

impl dyn View {
    /// Attempts to downcast `self` to a concrete type.
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.as_any().downcast_ref()
    }

    /// Attempts to downcast `self` to a concrete type.
    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
        self.as_any_mut().downcast_mut()
    }

    /// Attempts to downcast `Box<Self>` to a concrete type.
    pub fn downcast<T: Any>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
        // Do the check here + unwrap, so the error
        // value is `Self` and not `dyn Any`.
        if self.as_any().is::<T>() {
            Ok(self.as_boxed_any().downcast().unwrap())
        } else {
            Err(self)
        }
    }

    /// Checks if this view is of type `T`.
    pub fn is<T: Any>(&self) -> bool {
        self.as_any().is::<T>()
    }
}
<|endoftext|>