<commit_before><commit_msg>Added a new benchmark<commit_after>#![feature(test)]
extern crate test;
extern crate bytes;

mod tests {
    use test::Bencher;
    use bytes::{BytesMut, BufMut};

    #[bench]
    fn bench_parse_request(b : &mut Bencher) {
        let mut buffer = BytesMut::new();
        push(&mut buffer, b"GET / HTTP/1.1\nContent-Type: text/html\nContent-Length: 120\n\nHello World\n");

        b.iter(|| {
            // Clone buffer for iter
            let iter = buffer.clone();

            // Loop over bytes, to find line endings
            let mut it = iter.iter();
            let mut firstc : u16 = 0_u16;
            let mut headc : u16 = 0_u16;

            loop {
                // Check if end is reached
                match it.next() {
                    Some(&b'\n') => break,
                    None => break,
                    _ => {
                        firstc += 1;
                    }
                };
            }

            // Cache headers line length
            let mut linec : u16 = 0_u16;

            loop {
                // Check if end of headers reached
                match it.next() {
                    // On line end
                    Some(&b'\n') => {
                        // Headers end reached
                        if linec == 1 {
                            break;
                        }

                        // Increment total length
                        headc += 1;

                        // Reset line length
                        linec = 0;
                    },
                    // Buffer end
                    None => break,
                    _ => {
                        // Else increment length
                        linec += 1;
                        headc += 1;
                    }
                };
            }
        });
    }

    fn push(buf : &mut BytesMut, data : &[u8]) {
        buf.reserve(data.len());

        unsafe {
            buf.bytes_mut()[..data.len()].copy_from_slice(data);
            buf.advance_mut(data.len());
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add an id for state assignment<commit_after>pub type ID = [u16;12];

mod experiment{
    use std::iter::Iterator;
    #[derive(Copy, Clone, Show)]
    pub struct ID{
        data: [u8;15],
        end: u8
    }

    impl ID{
        pub fn new() -> ID{
            ID{
                data: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                end: 0
            }
        }
        ///push last component id back
        #[inline(always)]
        pub fn push(&mut self, i: u16){
            if self.end > 14{
                panic!("to many ids");
            }
            if i >= 32768{
                panic!("value given is to big to be stored, limit the number of components used");
            }
            if i < 128{
                self.data[self.end as usize] = i as u8;
                self.end += 1;
            }else{
                self.data[self.end as usize] = (i >> 1) as u8;
                self.data[(self.end +1) as usize] = (i >> 6) as u8;
                self.end += 2;
            }
        }

        ///get an iterator over all methods
        #[inline(always)]
        pub fn iter<'a>(&'a self) -> ID_Iterator<'a>{
            ID_Iterator{
                id: self,
                pos: 0
            }
        }
    }

    pub struct ID_Iterator<'a>{
        id: &'a ID,
        pos: u8,
    }
    impl<'a> Iterator for ID_Iterator<'a>{
        type Item = u16;
        fn next(&mut self) -> Option<u16>{
            None
        }
    }

    /*#[test]
    fn test_ID(){
        let mut id = ID::new();
        id.push(127);
        id.push(12);
        id.push(1023);
        assert!(id.end == 4, "end has wrong size");
        assert!(id.data[0] == 0b01111111, "wrong number {}", 0b01111111);
        assert!(id.data[1] == 12);
        assert!(id.data[2] == 0b11111111, "wront it is {}", id.data[2]);
        assert!(id.data[3] == 0b11100000, "wront it is {}", id.data[3]);
    }*/
}
<|endoftext|>


<commit_before><commit_msg>Add 2D plasticity example.<commit_after>extern crate nalgebra as na;
extern crate ncollide2d;
extern crate nphysics2d;
extern crate nphysics_testbed2d;

use std::sync::Arc;
use na::{Isometry2, Point2, Point3, Vector2};
use ncollide2d::shape::{Cuboid, ShapeHandle, Polyline};
use nphysics2d::object::{BodyPartHandle, Material, DeformableSurface, BodyHandle, BodyStatus, BodyPart};
use nphysics2d::world::World;
use nphysics2d::volumetric::Volumetric;
use nphysics2d::math::Inertia;
use nphysics_testbed2d::Testbed;

const COLLIDER_MARGIN: f32 = 0.005;

fn main() {
    /*
     * World
     */
    let mut world = World::new();

    /*
     * Ground.
     */
    let platform_height = 0.4;
    let platform_size = 0.6;
    let platform_shape =
        ShapeHandle::new(Cuboid::new(Vector2::new(0.03, 0.03)));

    let positions = [
        Isometry2::new(Vector2::new(0.4, platform_height), na::zero()),
        Isometry2::new(Vector2::new(0.2, -platform_height), na::zero()),
        Isometry2::new(Vector2::new(0.0, platform_height), na::zero()),
        Isometry2::new(Vector2::new(-0.2, -platform_height), na::zero()),
        Isometry2::new(Vector2::new(-0.4, platform_height), na::zero()),
    ];

    let mut platforms = [BodyHandle::ground(); 5];

    for (i, pos) in positions.iter().enumerate() {
        // NOTE: it is OK to set an inertia equal to zero for a body that will only be kinematic.
        let part = world.add_rigid_body(*pos, Inertia::zero(), Point2::origin());
        world.body_mut(part.body_handle).set_status(BodyStatus::Kinematic);

        world.add_collider(
            COLLIDER_MARGIN,
            platform_shape.clone(),
            part,
            Isometry2::identity(),
            Material::default(),
        );

        platforms[i] = part.body_handle;
    }

    /*
     * Create the deformable body and a collider for its contour.
     */
    let mut volume = DeformableSurface::quad(
        &Isometry2::identity(),
        &Vector2::new(1.1, 0.1),
        50, 1,
        1.0, 1.0e2, 0.0,
        (0.2, 0.0));
    let (mesh, ids_map, parts_map) = volume.boundary_polyline();
    volume.renumber_dofs(&ids_map);
    volume.set_plasticity(0.1, 20.0, 1.0e5);

    let deformable_handle = world.add_body(Box::new(volume));
    world.add_deformable_collider(
        COLLIDER_MARGIN,
        mesh,
        deformable_handle,
        None,
        Some(Arc::new(parts_map)),
        Material::default(),
    );
    world.body_mut(deformable_handle).set_deactivation_threshold(None);

    /*
     * Set up the testbed.
     */
    let mut testbed = Testbed::new(world);
    testbed.set_body_color(deformable_handle, Point3::new(0.0, 0.0, 1.0));

    for platform in &platforms {
        testbed.set_body_color(*platform, Point3::new(0.5, 0.5, 0.5));
    }

    testbed.add_callback(move |world, _, time| {
        for (i, handle) in platforms.iter().enumerate() {
            let platform = world.rigid_body_mut(*handle).unwrap();
            let platform_y = platform.position().translation.vector.y;

            let mut vel = platform.velocity();
            let vel_magnitude = 0.1;
            let max_traversal = 0.005;

            if i % 2 == 0 {
                if platform_y <= -max_traversal {
                    vel.linear.y = vel_magnitude;
                } else if platform_y >= platform_height {
                    vel.linear.y = -vel_magnitude;
                }
            } else {
                if platform_y >= max_traversal {
                    vel.linear.y = -vel_magnitude;
                } else if platform_y <= -platform_height {
                    vel.linear.y = vel_magnitude;
                }
            }

            platform.set_velocity(vel);
        }
    });

    // testbed.hide_performance_counters();
//    testbed.look_at(Point3::new(0.0, 0.0, 2.0), Point3::new(0.0, 0.0, 0.0));
    testbed.run();
}
<|endoftext|>


<commit_before>use std::fmt;

use chrono::{DateTime, Local};
use chrono_humanize::HumanTime;
use json::JsonValue;

// #[derive(Debug, Default)]
// pub struct Error {
//     pub detail: String,
// }
//
// #[derive(Debug)]
// pub struct CrateLinks {
//     pub owners: Option<String>,
//     pub reverse_dependencies: String,
//     pub version_downloads: String,
//     pub versions: Option<String>,
// }
//
// pub struct Crate {
//     pub created_at: String,
//     pub description: Option<String>,
//     pub documentation: Option<String>,
//     pub downloads: i32,
//     pub homepage: Option<String>,
//     pub id: String,
//     pub keywords: Option<Vec<String>>,
//     pub license: Option<String>,
//     pub links: CrateLinks,
//     pub max_version: String,
//     pub name: String,
//     pub repository: Option<String>,
//     pub updated_at: String,
//     pub versions: Option<Vec<u64>>,
// }
//
// #[derive(Debug)]
// pub struct Keyword {
//     pub crates_cnt: u64,
//     pub created_at: String,
//     pub id: String,
//     pub keyword: String,
// }
//
// #[derive(Debug)]
// pub struct VersionLinks {
//     pub authors: String,
//     pub dependencies: String,
//     pub version_downloads: String,
// }
//
// #[derive(Debug)]
// pub struct Version {
//     pub krate: String,
//     pub created_at: String,
//     pub dl_path: String,
//     pub downloads: i32,
//     pub features: HashMap<String, Vec<String>>,
//     pub id: i32,
//     pub links: VersionLinks,
//     pub num: String,
//     pub updated_at: String,
//     pub yanked: bool,
// }
//
// pub struct Reply {
//     pub errors: Error,
//     pub krate: Crate,
//     pub keywords: Vec<Keyword>,
//     pub versions: Vec<Version>,
// }

struct TimeStamp(Option<DateTime<Local>>);

impl<'a> From<&'a JsonValue> for TimeStamp {
    fn from(jv: &JsonValue) -> Self {
        let parse = |s: &str| s.parse::<DateTime<Local>>().ok();
        TimeStamp(jv.as_str().and_then(parse))
    }
}

impl fmt::Display for TimeStamp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ts) = self.0 {
            if f.alternate() {
                f.pad(&format!("{}", HumanTime::from(ts)))
            } else {
                f.pad(&format!("{}", ts.naive_local()))
            }
        } else {
            f.pad("")
        }
    }
}

pub struct Crate {
    krate: JsonValue,
    versions: JsonValue,
    keywords: JsonValue,
}

const FIELDS: [&'static str; 5] =
    ["description", "documentation", "homepage", "repository", "license"];

impl Crate {
    pub fn new(json: &JsonValue) -> Self {
        let mut krate = json["crate"].clone();
        // Fix up fields that may be absent

        for field in &FIELDS {
            if krate[*field].is_null() {
                krate[*field] = "".into();
            }
        }

        Crate {
            krate: krate,
            versions: json["versions"].clone(),
            keywords: json["keywords"].clone(),
        }
    }

    pub fn print_repository(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Repository:", self.krate["repository"])
        } else {
            format!("{}", self.krate["repository"])
        }
        // if let JsonValue::String(ref repository) = self.krate["repository"] {
        //     if verbose {
        //         format!("{:<16}{}", "Repository:", repository)
        //     } else {
        //         repository.clone()
        //     }
        // }
    }

    pub fn print_documentation(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Documentation:", self.krate["documentation"])
        } else {
            format!("{}", self.krate["documentation"])
        }
        // if let JsonValue::String(ref documentation) = self.krate["documentation"] {
        //     if verbose {
        //         format!("{:<16}{}", "Documentation:", documentation)
        //     } else {
        //         documentation.clone()
        //     }
        // }
    }

    pub fn print_downloads(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Downloads:", self.krate["downloads"])
        } else {
            format!("{}", self.krate["downloads"])
        }
        // if let JsonValue::Number(downloads) = self.krate["downloads"] {
        //     if verbose {
        //         format!("{:<16}{}", "Downloads:", downloads)
        //     } else {
        //         format!("{}", downloads)
        //     }
        // }
    }

    pub fn print_homepage(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Homepage:", self.krate["homepage"])
        } else {
            format!("{}", self.krate["homepage"])
        }
        // if let JsonValue::String(ref homepage) = self.krate["homepage"] {
        //     let fmt = if verbose {
        //         format!("{:<16}{}", "Homepage:", homepage)
        //     } else {
        //         homepage.clone()
        //     };
        //     println!("{}", fmt);
        // }
    }

    fn print_version(v: &JsonValue, verbose: bool) -> String {
        let created_at = TimeStamp::from(&v["created_at"]);
        let mut output = format!("{:<11}{:<#16}{:<11}", v["num"], created_at, v["downloads"]);

        if v["yanked"] == "true" {
            output = output + "(yanked)";
        }

        if verbose {
            // Consider adding some more useful information in verbose mode
            output + "\n"
        } else {
            output + "\n"
        }
    }

    fn print_version_header(verbose: bool) -> String {
        let output = format!("{:<11}{:<#16}{:<11}\n", "VERSION", "RELEASED", "DOWNLOADS");
        if verbose {
            // Consider adding some more useful information in verbose mode
            output + "\n"
        } else {
            output + "\n"
        }
    }

    pub fn print_last_versions(&self, limit: usize, verbose: bool) -> String {
        let mut output = Crate::print_version_header(verbose);
        for version in self.versions.members().take(limit) {
            output = output + &Crate::print_version(version, verbose);
        }
        let length = self.versions.len();
        if limit < length {
            output = output + &format!("\n... use -VV to show all {} versions\n", length);
        }
        output
    }

    pub fn print_keywords(&self, verbose: bool) -> String {
        if verbose {
            format!("{:#}", self.keywords)
        } else {
            format!("{}", self.keywords)
        }
    }
}

impl fmt::Display for Crate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let created_at = TimeStamp::from(&self.krate["created_at"]);
        let updated_at = TimeStamp::from(&self.krate["updated_at"]);

        let keywords = self.krate["keywords"]
            .members()
            .filter_map(|jv| jv.as_str())
            .collect::<Vec<_>>();

        if f.alternate() {
            write!(f,
                   "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
                   format_args!("{:<16}{}", "Crate:", self.krate["name"]),
                   format_args!("{:<16}{}", "Version:", self.krate["max_version"]),
                   format_args!("{:<16}{}", "Description:", self.krate["description"]),
                   format_args!("{:<16}{}", "Downloads:", self.krate["downloads"]),
                   format_args!("{:<16}{}", "Homepage:", self.krate["homepage"]),
                   format_args!("{:<16}{}", "Documentation:", self.krate["documentation"]),
                   format_args!("{:<16}{}", "Repository:", self.krate["repository"]),
                   format_args!("{:<16}{}", "License:", self.krate["license"]),
                   format_args!("{:<16}{:?}", "Keywords:", keywords),
                   format_args!("{:<16}{}  ({:#})", "Created at:", created_at, created_at),
                   format_args!("{:<16}{}  ({:#})", "Updated at:", updated_at, updated_at))
        } else {
            let mut versions = String::new();
            for line in self.print_last_versions(5, false).lines() {
                versions = versions + "\n";
                if !line.is_empty() {
                    versions = versions + "  " + line;
                }
            }

            write!(f,
                   "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
                   format_args!("{:<16}{}", "Crate:", self.krate["name"]),
                   format_args!("{:<16}{}", "Version:", self.krate["max_version"]),
                   format_args!("{:<16}{}", "Description:", self.krate["description"]),
                   format_args!("{:<16}{}", "Downloads:", self.krate["downloads"]),
                   format_args!("{:<16}{}", "Homepage:", self.krate["homepage"]),
                   format_args!("{:<16}{}", "Documentation:", self.krate["documentation"]),
                   format_args!("{:<16}{}", "Repository:", self.krate["repository"]),
                   format_args!("{:<16}{:#}", "Last updated:", updated_at),
                   format_args!("{:<16}\n{}", "Version history:", versions))
        }
    }
}
<commit_msg>Fix displaying yanked versions<commit_after>use std::fmt;

use chrono::{DateTime, Local};
use chrono_humanize::HumanTime;
use json::JsonValue;

// #[derive(Debug, Default)]
// pub struct Error {
//     pub detail: String,
// }
//
// #[derive(Debug)]
// pub struct CrateLinks {
//     pub owners: Option<String>,
//     pub reverse_dependencies: String,
//     pub version_downloads: String,
//     pub versions: Option<String>,
// }
//
// pub struct Crate {
//     pub created_at: String,
//     pub description: Option<String>,
//     pub documentation: Option<String>,
//     pub downloads: i32,
//     pub homepage: Option<String>,
//     pub id: String,
//     pub keywords: Option<Vec<String>>,
//     pub license: Option<String>,
//     pub links: CrateLinks,
//     pub max_version: String,
//     pub name: String,
//     pub repository: Option<String>,
//     pub updated_at: String,
//     pub versions: Option<Vec<u64>>,
// }
//
// #[derive(Debug)]
// pub struct Keyword {
//     pub crates_cnt: u64,
//     pub created_at: String,
//     pub id: String,
//     pub keyword: String,
// }
//
// #[derive(Debug)]
// pub struct VersionLinks {
//     pub authors: String,
//     pub dependencies: String,
//     pub version_downloads: String,
// }
//
// #[derive(Debug)]
// pub struct Version {
//     pub krate: String,
//     pub created_at: String,
//     pub dl_path: String,
//     pub downloads: i32,
//     pub features: HashMap<String, Vec<String>>,
//     pub id: i32,
//     pub links: VersionLinks,
//     pub num: String,
//     pub updated_at: String,
//     pub yanked: bool,
// }
//
// pub struct Reply {
//     pub errors: Error,
//     pub krate: Crate,
//     pub keywords: Vec<Keyword>,
//     pub versions: Vec<Version>,
// }

struct TimeStamp(Option<DateTime<Local>>);

impl<'a> From<&'a JsonValue> for TimeStamp {
    fn from(jv: &JsonValue) -> Self {
        let parse = |s: &str| s.parse::<DateTime<Local>>().ok();
        TimeStamp(jv.as_str().and_then(parse))
    }
}

impl fmt::Display for TimeStamp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ts) = self.0 {
            if f.alternate() {
                f.pad(&format!("{}", HumanTime::from(ts)))
            } else {
                f.pad(&format!("{}", ts.naive_local()))
            }
        } else {
            f.pad("")
        }
    }
}

pub struct Crate {
    krate: JsonValue,
    versions: JsonValue,
    keywords: JsonValue,
}

const FIELDS: [&'static str; 5] =
    ["description", "documentation", "homepage", "repository", "license"];

impl Crate {
    pub fn new(json: &JsonValue) -> Self {
        let mut krate = json["crate"].clone();
        // Fix up fields that may be absent

        for field in &FIELDS {
            if krate[*field].is_null() {
                krate[*field] = "".into();
            }
        }

        Crate {
            krate: krate,
            versions: json["versions"].clone(),
            keywords: json["keywords"].clone(),
        }
    }

    pub fn print_repository(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Repository:", self.krate["repository"])
        } else {
            format!("{}", self.krate["repository"])
        }
        // if let JsonValue::String(ref repository) = self.krate["repository"] {
        //     if verbose {
        //         format!("{:<16}{}", "Repository:", repository)
        //     } else {
        //         repository.clone()
        //     }
        // }
    }

    pub fn print_documentation(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Documentation:", self.krate["documentation"])
        } else {
            format!("{}", self.krate["documentation"])
        }
        // if let JsonValue::String(ref documentation) = self.krate["documentation"] {
        //     if verbose {
        //         format!("{:<16}{}", "Documentation:", documentation)
        //     } else {
        //         documentation.clone()
        //     }
        // }
    }

    pub fn print_downloads(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Downloads:", self.krate["downloads"])
        } else {
            format!("{}", self.krate["downloads"])
        }
        // if let JsonValue::Number(downloads) = self.krate["downloads"] {
        //     if verbose {
        //         format!("{:<16}{}", "Downloads:", downloads)
        //     } else {
        //         format!("{}", downloads)
        //     }
        // }
    }

    pub fn print_homepage(&self, verbose: bool) -> String {
        if verbose {
            format!("{:<16}{}", "Homepage:", self.krate["homepage"])
        } else {
            format!("{}", self.krate["homepage"])
        }
        // if let JsonValue::String(ref homepage) = self.krate["homepage"] {
        //     let fmt = if verbose {
        //         format!("{:<16}{}", "Homepage:", homepage)
        //     } else {
        //         homepage.clone()
        //     };
        //     println!("{}", fmt);
        // }
    }

    fn print_version(v: &JsonValue, verbose: bool) -> String {
        let created_at = TimeStamp::from(&v["created_at"]);
        let mut output = format!("{:<11}{:<#16}{:<11}", v["num"], created_at, v["downloads"]);

        if v["yanked"].as_bool() == Some(true) {
            output = output + "\t\t(yanked)";
        }

        if verbose {
            // Consider adding some more useful information in verbose mode
            output + "\n"
        } else {
            output + "\n"
        }
    }

    fn print_version_header(verbose: bool) -> String {
        let output = format!("{:<11}{:<#16}{:<11}\n", "VERSION", "RELEASED", "DOWNLOADS");
        if verbose {
            // Consider adding some more useful information in verbose mode
            output + "\n"
        } else {
            output + "\n"
        }
    }

    pub fn print_last_versions(&self, limit: usize, verbose: bool) -> String {
        let mut output = Crate::print_version_header(verbose);
        for version in self.versions.members().take(limit) {
            output = output + &Crate::print_version(version, verbose);
        }
        let length = self.versions.len();
        if limit < length {
            output = output + &format!("\n... use -VV to show all {} versions\n", length);
        }
        output
    }

    pub fn print_keywords(&self, verbose: bool) -> String {
        if verbose {
            format!("{:#}", self.keywords)
        } else {
            format!("{}", self.keywords)
        }
    }
}

impl fmt::Display for Crate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let created_at = TimeStamp::from(&self.krate["created_at"]);
        let updated_at = TimeStamp::from(&self.krate["updated_at"]);

        let keywords = self.krate["keywords"]
            .members()
            .filter_map(|jv| jv.as_str())
            .collect::<Vec<_>>();

        if f.alternate() {
            write!(f,
                   "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
                   format_args!("{:<16}{}", "Crate:", self.krate["name"]),
                   format_args!("{:<16}{}", "Version:", self.krate["max_version"]),
                   format_args!("{:<16}{}", "Description:", self.krate["description"]),
                   format_args!("{:<16}{}", "Downloads:", self.krate["downloads"]),
                   format_args!("{:<16}{}", "Homepage:", self.krate["homepage"]),
                   format_args!("{:<16}{}", "Documentation:", self.krate["documentation"]),
                   format_args!("{:<16}{}", "Repository:", self.krate["repository"]),
                   format_args!("{:<16}{}", "License:", self.krate["license"]),
                   format_args!("{:<16}{:?}", "Keywords:", keywords),
                   format_args!("{:<16}{}  ({:#})", "Created at:", created_at, created_at),
                   format_args!("{:<16}{}  ({:#})", "Updated at:", updated_at, updated_at))
        } else {
            let mut versions = String::new();
            for line in self.print_last_versions(5, false).lines() {
                versions = versions + "\n";
                if !line.is_empty() {
                    versions = versions + "  " + line;
                }
            }

            write!(f,
                   "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
                   format_args!("{:<16}{}", "Crate:", self.krate["name"]),
                   format_args!("{:<16}{}", "Version:", self.krate["max_version"]),
                   format_args!("{:<16}{}", "Description:", self.krate["description"]),
                   format_args!("{:<16}{}", "Downloads:", self.krate["downloads"]),
                   format_args!("{:<16}{}", "Homepage:", self.krate["homepage"]),
                   format_args!("{:<16}{}", "Documentation:", self.krate["documentation"]),
                   format_args!("{:<16}{}", "Repository:", self.krate["repository"]),
                   format_args!("{:<16}{:#}", "Last updated:", updated_at),
                   format_args!("{:<16}\n{}", "Version history:", versions))
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a regression test<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// compile-flags: -O
// Regression test for https://github.com/rust-lang/rust/issues/33868

#[repr(C)]
pub struct S {
    a: u32,
    b: f32,
    c: u32
}

#[no_mangle]
#[inline(never)]
pub extern "C" fn test(s: S) -> u32 {
    s.c
}

fn main() {
    assert_eq!(test(S{a: 0, b: 0.0, c: 42}), 42);
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #70539 - DutchGhost:test-62220, r=Dylan-DPC<commit_after>// build-pass
#![allow(incomplete_features)]

#![feature(const_generics)]
pub struct Vector<T, const N: usize>([T; N]);

pub type TruncatedVector<T, const N: usize> = Vector<T, { N - 1 }>;

impl<T, const N: usize> Vector<T, { N }> {
    /// Drop the last component and return the vector with one fewer dimension.
    pub fn trunc(self) -> (TruncatedVector<T, { N }>, T) {
        unimplemented!()
    }
}

fn vec4<T>(a: T, b: T, c: T, d: T) -> Vector<T, 4> {
    Vector([a, b, c, d])
}

fn main() {
    let (_xyz, _w): (TruncatedVector<u32, 4>, u32) = vec4(0u32, 1, 2, 3).trunc();
}
<|endoftext|>


<commit_before><commit_msg>Do not use & in pattern matching<commit_after><|endoftext|>


<commit_before><commit_msg>Test that column information is not emitted for MSVC targets<commit_after>// Verify that no column information is emitted for MSVC targets
//
// only-msvc
// compile-flags: -C debuginfo=2

// CHECK-NOT: !DILexicalBlock({{.*}}column: {{.*}})
// CHECK-NOT: !DILocation({{.*}}column: {{.*}})

pub fn add(a: u32, b: u32) -> u32 {
    a + b
}

fn main() {
    let c = add(1, 2);
    println!("{}", c);
}
<|endoftext|>


<commit_before><commit_msg>Add "cheating" http server example.<commit_after>extern crate mioco;
extern crate env_logger;

use std::net::SocketAddr;
use std::str::FromStr;
use std::io::Write;
use mioco::mio::tcp::{TcpSocket};

const DEFAULT_LISTEN_ADDR : &'static str = "127.0.0.1:5555";

fn listend_addr() -> SocketAddr {
    FromStr::from_str(DEFAULT_LISTEN_ADDR).unwrap()
}

const RESPONSE: &'static str = "HTTP/1.1 200 OK\r
Content-Length: 14\r
\r
Hello World\r
\r";

fn main() {
    env_logger::init().unwrap();
    let addr = listend_addr();

    let sock = TcpSocket::v4().unwrap();
    sock.bind(&addr).unwrap();
    let sock = sock.listen(1024).unwrap();

    println!("Starting \"cheating\" http server on {:?}", sock.local_addr().unwrap());

    mioco::start(move |mioco| {
        for _ in 0..8 {
            let sock = try!(sock.try_clone());
            mioco.spawn(move |mioco| {
                let sock = mioco.wrap(sock);
                loop {
                    let conn = try!(sock.accept());
                    mioco.spawn(move |mioco| {
                        let mut conn = mioco.wrap(conn);
                        loop {
                            let _ = try!(conn.write(&RESPONSE.as_bytes()));
                        }
                    });
                }
            });
        }
        Ok(())
    });
}
<|endoftext|>


<commit_before><commit_msg>add test for nested deprecated<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(deprecated)]
#![allow(warnings)]

#[deprecated]
fn issue_35128() {
    format_args!("foo");
}

#[deprecated]
fn issue_35128_minimal() {
    static FOO: &'static str = "foo";
    let _ = FOO;
}

#[deprecated]
mod silent {
    type DeprecatedType = u8;
    struct DeprecatedStruct;
    fn deprecated_fn() {}
    trait DeprecatedTrait {}
    static DEPRECATED_STATIC: u8 = 0;
    const DEPRECATED_CONST: u8 = 1;

    struct Foo(DeprecatedType);

    impl DeprecatedTrait for Foo {}

    impl Foo {
        fn bar<T: DeprecatedTrait>() {
            deprecated_fn();
        }
    }

    fn foo() -> u8 {
        DEPRECATED_STATIC +
        DEPRECATED_CONST
    }
}

#[deprecated]
mod loud {
    #[deprecated]
    type DeprecatedType = u8;
    #[deprecated]
    struct DeprecatedStruct;
    #[deprecated]
    fn deprecated_fn() {}
    #[deprecated]
    trait DeprecatedTrait {}
    #[deprecated]
    static DEPRECATED_STATIC: u8 = 0;
    #[deprecated]
    const DEPRECATED_CONST: u8 = 1;

    struct Foo(DeprecatedType); //~ ERROR use of deprecated item

    impl DeprecatedTrait for Foo {} //~ ERROR use of deprecated item

    impl Foo {
        fn bar<T: DeprecatedTrait>() { //~ ERROR use of deprecated item
            deprecated_fn(); //~ ERROR use of deprecated item
        }
    }

    fn foo() -> u8 {
        DEPRECATED_STATIC + //~ ERROR use of deprecated item
        DEPRECATED_CONST //~ ERROR use of deprecated item
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>file.rs<commit_after>use std::sync::mpsc;
use std::thread;
use std::path::{Path, PathBuf};
use std::fs::{OpenOptions, File};
use std::io::{Cursor, Error, Seek, SeekFrom, Read, Write};

pub struct Writer {
    thread: thread::JoinHandle<()>,
    tx: mpsc::SyncSender<Msg>,
}

pub enum Msg {
    Seek(SeekFrom),
    Write(Vec<u8>),
    Finish,
}

impl Writer {
    pub fn new(filename: PathBuf) -> Writer {
        let (tx, rx) = mpsc::sync_channel(1024);
        let t = thread::spawn(move || {
            let mut f = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(false)
                .open(filename)
                .unwrap();

            loop {
                match rx.recv().unwrap() {
                    Msg::Seek(from) => {
                        f.seek(from).unwrap();
                    }
                    Msg::Write(buf) => {
                        f.write_all(&buf[..]).unwrap();
                    }
                    Msg::Finish => {
                        break;
                    }
                }
            }
        });
        Writer {
            thread: t,
            tx: tx,
        }
    }

    pub fn seek(&self, from: SeekFrom) {
        self.tx.send(Msg::Seek(from)).unwrap();
    }

    pub fn write_all(&self, buf: Vec<u8>) {
        self.tx.send(Msg::Write(buf)).unwrap();
    }

    pub fn close(self) {
        self.tx.send(Msg::Finish).unwrap_or_else(|e| error!("{:?}", e));
        if let Err(e) = self.thread.join() {
            error!("\n\n{:?}\n\n", e);
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Bugfix: changed u64 to size_t in malloc invocations<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Clap argument name<commit_after><|endoftext|>


<commit_before>//! Handles the `Enter` key press. At the momently, this only continues
//! comments, but should handle indent some time in the future as well.

use ide_db::base_db::{FilePosition, SourceDatabase};
use ide_db::RootDatabase;
use syntax::{
    algo::find_node_at_offset,
    ast::{self, edit::IndentLevel, AstToken},
    AstNode, SmolStr, SourceFile,
    SyntaxKind::*,
    SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset,
};

use text_edit::TextEdit;

// Feature: On Enter
//
// rust-analyzer can override kbd:[Enter] key to make it smarter:
//
// - kbd:[Enter] inside triple-slash comments automatically inserts `///`
// - kbd:[Enter] in the middle or after a trailing space in `//` inserts `//`
// - kbd:[Enter] inside `//!` doc comments automatically inserts `//!`
// - kbd:[Enter] after `{` indents contents and closing `}` of single-line block
//
// This action needs to be assigned to shortcut explicitly.
//
// VS Code::
//
// Add the following to `keybindings.json`:
// [source,json]
// ----
// {
//   "key": "Enter",
//   "command": "rust-analyzer.onEnter",
//   "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust"
// }
// ----
//
// image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[]
pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<TextEdit> {
    let parse = db.parse(position.file_id);
    let file = parse.tree();
    let token = file.syntax().token_at_offset(position.offset).left_biased()?;

    if let Some(comment) = ast::Comment::cast(token.clone()) {
        return on_enter_in_comment(&comment, &file, position.offset);
    }

    if token.kind() == L_CURLY {
        // Typing enter after the `{` of a block expression, where the `}` is on the same line
        if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
            .and_then(|block| on_enter_in_block(block, position))
        {
            cov_mark::hit!(indent_block_contents);
            return Some(edit);
        }

        // Typing enter after the `{` of a use tree list.
        if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
            .and_then(|list| on_enter_in_use_tree_list(list, position))
        {
            cov_mark::hit!(indent_block_contents);
            return Some(edit);
        }
    }

    None
}

fn on_enter_in_comment(
    comment: &ast::Comment,
    file: &ast::SourceFile,
    offset: TextSize,
) -> Option<TextEdit> {
    if comment.kind().shape.is_block() {
        return None;
    }

    let prefix = comment.prefix();
    let comment_range = comment.syntax().text_range();
    if offset < comment_range.start() + TextSize::of(prefix) {
        return None;
    }

    let mut remove_trailing_whitespace = false;
    // Continuing single-line non-doc comments (like this one :) ) is annoying
    if prefix == "//" && comment_range.end() == offset {
        if comment.text().ends_with(' ') {
            cov_mark::hit!(continues_end_of_line_comment_with_space);
            remove_trailing_whitespace = true;
        } else if !followed_by_comment(comment) {
            return None;
        }
    }

    let indent = node_indent(file, comment.syntax())?;
    let inserted = format!("\n{}{} $0", indent, prefix);
    let delete = if remove_trailing_whitespace {
        let trimmed_len = comment.text().trim_end().len() as u32;
        let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
        TextRange::new(offset - TextSize::from(trailing_whitespace_len), offset)
    } else {
        TextRange::empty(offset)
    };
    let edit = TextEdit::replace(delete, inserted);
    Some(edit)
}

fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<TextEdit> {
    let contents = block_contents(&block)?;

    if block.syntax().text().contains_char('\n') {
        return None;
    }

    let indent = IndentLevel::from_node(block.syntax());
    let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
    edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
    Some(edit)
}

fn on_enter_in_use_tree_list(list: ast::UseTreeList, position: FilePosition) -> Option<TextEdit> {
    if list.syntax().text().contains_char('\n') {
        return None;
    }

    let indent = IndentLevel::from_node(list.syntax());
    let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
    edit.union(TextEdit::insert(
        list.r_curly_token()?.text_range().start(),
        format!("\n{}", indent),
    ))
    .ok()?;
    Some(edit)
}

fn block_contents(block: &ast::BlockExpr) -> Option<SyntaxNode> {
    let mut node = block.tail_expr().map(|e| e.syntax().clone());

    for stmt in block.statements() {
        if node.is_some() {
            // More than 1 node in the block
            return None;
        }

        node = Some(stmt.syntax().clone());
    }

    node
}

fn followed_by_comment(comment: &ast::Comment) -> bool {
    let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
        Some(it) => it,
        None => return false,
    };
    if ws.spans_multiple_lines() {
        return false;
    }
    ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
}

fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
    let ws = match file.syntax().token_at_offset(token.text_range().start()) {
        TokenAtOffset::Between(l, r) => {
            assert!(r == *token);
            l
        }
        TokenAtOffset::Single(n) => {
            assert!(n == *token);
            return Some("".into());
        }
        TokenAtOffset::None => unreachable!(),
    };
    if ws.kind() != WHITESPACE {
        return None;
    }
    let text = ws.text();
    let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
    Some(text[pos..].into())
}

#[cfg(test)]
mod tests {
    use stdx::trim_indent;
    use test_utils::assert_eq_text;

    use crate::fixture;

    fn apply_on_enter(before: &str) -> Option<String> {
        let (analysis, position) = fixture::position(before);
        let result = analysis.on_enter(position).unwrap()?;

        let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
        result.apply(&mut actual);
        Some(actual)
    }

    fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
        let ra_fixture_after = &trim_indent(ra_fixture_after);
        let actual = apply_on_enter(ra_fixture_before).unwrap();
        assert_eq_text!(ra_fixture_after, &actual);
    }

    fn do_check_noop(ra_fixture_text: &str) {
        assert!(apply_on_enter(ra_fixture_text).is_none())
    }

    #[test]
    fn continues_doc_comment() {
        do_check(
            r"
/// Some docs$0
fn foo() {
}
",
            r"
/// Some docs
/// $0
fn foo() {
}
",
        );

        do_check(
            r"
impl S {
    /// Some$0 docs.
    fn foo() {}
}
",
            r"
impl S {
    /// Some
    /// $0 docs.
    fn foo() {}
}
",
        );

        do_check(
            r"
///$0 Some docs
fn foo() {
}
",
            r"
///
/// $0 Some docs
fn foo() {
}
",
        );
    }

    #[test]
    fn does_not_continue_before_doc_comment() {
        do_check_noop(r"$0//! docz");
    }

    #[test]
    fn continues_another_doc_comment() {
        do_check(
            r#"
fn main() {
    //! Documentation for$0 on enter
    let x = 1 + 1;
}
"#,
            r#"
fn main() {
    //! Documentation for
    //! $0 on enter
    let x = 1 + 1;
}
"#,
        );
    }

    #[test]
    fn continues_code_comment_in_the_middle_of_line() {
        do_check(
            r"
fn main() {
    // Fix$0 me
    let x = 1 + 1;
}
",
            r"
fn main() {
    // Fix
    // $0 me
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn continues_code_comment_in_the_middle_several_lines() {
        do_check(
            r"
fn main() {
    // Fix$0
    // me
    let x = 1 + 1;
}
",
            r"
fn main() {
    // Fix
    // $0
    // me
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn does_not_continue_end_of_line_comment() {
        do_check_noop(
            r"
fn main() {
    // Fix me$0
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn continues_end_of_line_comment_with_space() {
        cov_mark::check!(continues_end_of_line_comment_with_space);
        do_check(
            r#"
fn main() {
    // Fix me $0
    let x = 1 + 1;
}
"#,
            r#"
fn main() {
    // Fix me
    // $0
    let x = 1 + 1;
}
"#,
        );
    }

    #[test]
    fn trims_all_trailing_whitespace() {
        do_check(
            "
fn main() {
    // Fix me  \t\t   $0
    let x = 1 + 1;
}
",
            "
fn main() {
    // Fix me
    // $0
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn indents_fn_body_block() {
        cov_mark::check!(indent_block_contents);
        do_check(
            r#"
fn f() {$0()}
        "#,
            r#"
fn f() {
    $0()
}
        "#,
        );
    }

    #[test]
    fn indents_block_expr() {
        do_check(
            r#"
fn f() {
    let x = {$0()};
}
        "#,
            r#"
fn f() {
    let x = {
        $0()
    };
}
        "#,
        );
    }

    #[test]
    fn indents_match_arm() {
        do_check(
            r#"
fn f() {
    match 6 {
        1 => {$0f()},
        _ => (),
    }
}
        "#,
            r#"
fn f() {
    match 6 {
        1 => {
            $0f()
        },
        _ => (),
    }
}
        "#,
        );
    }

    #[test]
    fn indents_block_with_statement() {
        do_check(
            r#"
fn f() {$0a = b}
        "#,
            r#"
fn f() {
    $0a = b
}
        "#,
        );
        do_check(
            r#"
fn f() {$0fn f() {}}
        "#,
            r#"
fn f() {
    $0fn f() {}
}
        "#,
        );
    }

    #[test]
    fn indents_nested_blocks() {
        do_check(
            r#"
fn f() {$0{}}
        "#,
            r#"
fn f() {
    $0{}
}
        "#,
        );
    }

    #[test]
    fn does_not_indent_empty_block() {
        do_check_noop(
            r#"
fn f() {$0}
        "#,
        );
        do_check_noop(
            r#"
fn f() {{$0}}
        "#,
        );
    }

    #[test]
    fn does_not_indent_block_with_too_much_content() {
        do_check_noop(
            r#"
fn f() {$0 a = b; ()}
        "#,
        );
        do_check_noop(
            r#"
fn f() {$0 a = b; a = b; }
        "#,
        );
    }

    #[test]
    fn does_not_indent_multiline_block() {
        do_check_noop(
            r#"
fn f() {$0
}
        "#,
        );
        do_check_noop(
            r#"
fn f() {$0

}
        "#,
        );
    }

    #[test]
    fn indents_use_tree_list() {
        do_check(
            r#"
use crate::{$0};
            "#,
            r#"
use crate::{
    $0
};
            "#,
        );
        do_check(
            r#"
use crate::{$0Object, path::to::OtherThing};
            "#,
            r#"
use crate::{
    $0Object, path::to::OtherThing
};
            "#,
        );
        do_check(
            r#"
use {crate::{$0Object, path::to::OtherThing}};
            "#,
            r#"
use {crate::{
    $0Object, path::to::OtherThing
}};
            "#,
        );
        do_check(
            r#"
use {
    crate::{$0Object, path::to::OtherThing}
};
            "#,
            r#"
use {
    crate::{
        $0Object, path::to::OtherThing
    }
};
            "#,
        );
    }

    #[test]
    fn does_not_indent_use_tree_list_when_not_at_curly_brace() {
        do_check_noop(
            r#"
use path::{Thing$0};
            "#,
        );
    }

    #[test]
    fn does_not_indent_use_tree_list_without_curly_braces() {
        do_check_noop(
            r#"
use path::Thing$0;
            "#,
        );
        do_check_noop(
            r#"
use path::$0Thing;
            "#,
        );
        do_check_noop(
            r#"
use path::Thing$0};
            "#,
        );
        do_check_noop(
            r#"
use path::{$0Thing;
            "#,
        );
    }

    #[test]
    fn does_not_indent_multiline_use_tree_list() {
        do_check_noop(
            r#"
use path::{$0
    Thing
};
            "#,
        );
    }
}
<commit_msg>docs: add note about `vscode-vim` in `on_enter`<commit_after>//! Handles the `Enter` key press. At the momently, this only continues
//! comments, but should handle indent some time in the future as well.

use ide_db::base_db::{FilePosition, SourceDatabase};
use ide_db::RootDatabase;
use syntax::{
    algo::find_node_at_offset,
    ast::{self, edit::IndentLevel, AstToken},
    AstNode, SmolStr, SourceFile,
    SyntaxKind::*,
    SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset,
};

use text_edit::TextEdit;

// Feature: On Enter
//
// rust-analyzer can override kbd:[Enter] key to make it smarter:
//
// - kbd:[Enter] inside triple-slash comments automatically inserts `///`
// - kbd:[Enter] in the middle or after a trailing space in `//` inserts `//`
// - kbd:[Enter] inside `//!` doc comments automatically inserts `//!`
// - kbd:[Enter] after `{` indents contents and closing `}` of single-line block
//
// This action needs to be assigned to shortcut explicitly.
//
// VS Code::
//
// Add the following to `keybindings.json`:
// [source,json]
// ----
// {
//   "key": "Enter",
//   "command": "rust-analyzer.onEnter",
//   "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust"
// }
// ----
//
// When using the Vim plugin:
// [source,json]
// ----
// {
//   "key": "Enter",
//   "command": "rust-analyzer.onEnter",
//   "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust && vim.mode == 'Insert'"
// }
// ----
//
// image::https://user-images.githubusercontent.com/48062697/113065578-04c21800-91b1-11eb-82b8-22b8c481e645.gif[]
pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<TextEdit> {
    let parse = db.parse(position.file_id);
    let file = parse.tree();
    let token = file.syntax().token_at_offset(position.offset).left_biased()?;

    if let Some(comment) = ast::Comment::cast(token.clone()) {
        return on_enter_in_comment(&comment, &file, position.offset);
    }

    if token.kind() == L_CURLY {
        // Typing enter after the `{` of a block expression, where the `}` is on the same line
        if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
            .and_then(|block| on_enter_in_block(block, position))
        {
            cov_mark::hit!(indent_block_contents);
            return Some(edit);
        }

        // Typing enter after the `{` of a use tree list.
        if let Some(edit) = find_node_at_offset(file.syntax(), position.offset - TextSize::of('{'))
            .and_then(|list| on_enter_in_use_tree_list(list, position))
        {
            cov_mark::hit!(indent_block_contents);
            return Some(edit);
        }
    }

    None
}

fn on_enter_in_comment(
    comment: &ast::Comment,
    file: &ast::SourceFile,
    offset: TextSize,
) -> Option<TextEdit> {
    if comment.kind().shape.is_block() {
        return None;
    }

    let prefix = comment.prefix();
    let comment_range = comment.syntax().text_range();
    if offset < comment_range.start() + TextSize::of(prefix) {
        return None;
    }

    let mut remove_trailing_whitespace = false;
    // Continuing single-line non-doc comments (like this one :) ) is annoying
    if prefix == "//" && comment_range.end() == offset {
        if comment.text().ends_with(' ') {
            cov_mark::hit!(continues_end_of_line_comment_with_space);
            remove_trailing_whitespace = true;
        } else if !followed_by_comment(comment) {
            return None;
        }
    }

    let indent = node_indent(file, comment.syntax())?;
    let inserted = format!("\n{}{} $0", indent, prefix);
    let delete = if remove_trailing_whitespace {
        let trimmed_len = comment.text().trim_end().len() as u32;
        let trailing_whitespace_len = comment.text().len() as u32 - trimmed_len;
        TextRange::new(offset - TextSize::from(trailing_whitespace_len), offset)
    } else {
        TextRange::empty(offset)
    };
    let edit = TextEdit::replace(delete, inserted);
    Some(edit)
}

fn on_enter_in_block(block: ast::BlockExpr, position: FilePosition) -> Option<TextEdit> {
    let contents = block_contents(&block)?;

    if block.syntax().text().contains_char('\n') {
        return None;
    }

    let indent = IndentLevel::from_node(block.syntax());
    let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
    edit.union(TextEdit::insert(contents.text_range().end(), format!("\n{}", indent))).ok()?;
    Some(edit)
}

fn on_enter_in_use_tree_list(list: ast::UseTreeList, position: FilePosition) -> Option<TextEdit> {
    if list.syntax().text().contains_char('\n') {
        return None;
    }

    let indent = IndentLevel::from_node(list.syntax());
    let mut edit = TextEdit::insert(position.offset, format!("\n{}$0", indent + 1));
    edit.union(TextEdit::insert(
        list.r_curly_token()?.text_range().start(),
        format!("\n{}", indent),
    ))
    .ok()?;
    Some(edit)
}

fn block_contents(block: &ast::BlockExpr) -> Option<SyntaxNode> {
    let mut node = block.tail_expr().map(|e| e.syntax().clone());

    for stmt in block.statements() {
        if node.is_some() {
            // More than 1 node in the block
            return None;
        }

        node = Some(stmt.syntax().clone());
    }

    node
}

fn followed_by_comment(comment: &ast::Comment) -> bool {
    let ws = match comment.syntax().next_token().and_then(ast::Whitespace::cast) {
        Some(it) => it,
        None => return false,
    };
    if ws.spans_multiple_lines() {
        return false;
    }
    ws.syntax().next_token().and_then(ast::Comment::cast).is_some()
}

fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
    let ws = match file.syntax().token_at_offset(token.text_range().start()) {
        TokenAtOffset::Between(l, r) => {
            assert!(r == *token);
            l
        }
        TokenAtOffset::Single(n) => {
            assert!(n == *token);
            return Some("".into());
        }
        TokenAtOffset::None => unreachable!(),
    };
    if ws.kind() != WHITESPACE {
        return None;
    }
    let text = ws.text();
    let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
    Some(text[pos..].into())
}

#[cfg(test)]
mod tests {
    use stdx::trim_indent;
    use test_utils::assert_eq_text;

    use crate::fixture;

    fn apply_on_enter(before: &str) -> Option<String> {
        let (analysis, position) = fixture::position(before);
        let result = analysis.on_enter(position).unwrap()?;

        let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
        result.apply(&mut actual);
        Some(actual)
    }

    fn do_check(ra_fixture_before: &str, ra_fixture_after: &str) {
        let ra_fixture_after = &trim_indent(ra_fixture_after);
        let actual = apply_on_enter(ra_fixture_before).unwrap();
        assert_eq_text!(ra_fixture_after, &actual);
    }

    fn do_check_noop(ra_fixture_text: &str) {
        assert!(apply_on_enter(ra_fixture_text).is_none())
    }

    #[test]
    fn continues_doc_comment() {
        do_check(
            r"
/// Some docs$0
fn foo() {
}
",
            r"
/// Some docs
/// $0
fn foo() {
}
",
        );

        do_check(
            r"
impl S {
    /// Some$0 docs.
    fn foo() {}
}
",
            r"
impl S {
    /// Some
    /// $0 docs.
    fn foo() {}
}
",
        );

        do_check(
            r"
///$0 Some docs
fn foo() {
}
",
            r"
///
/// $0 Some docs
fn foo() {
}
",
        );
    }

    #[test]
    fn does_not_continue_before_doc_comment() {
        do_check_noop(r"$0//! docz");
    }

    #[test]
    fn continues_another_doc_comment() {
        do_check(
            r#"
fn main() {
    //! Documentation for$0 on enter
    let x = 1 + 1;
}
"#,
            r#"
fn main() {
    //! Documentation for
    //! $0 on enter
    let x = 1 + 1;
}
"#,
        );
    }

    #[test]
    fn continues_code_comment_in_the_middle_of_line() {
        do_check(
            r"
fn main() {
    // Fix$0 me
    let x = 1 + 1;
}
",
            r"
fn main() {
    // Fix
    // $0 me
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn continues_code_comment_in_the_middle_several_lines() {
        do_check(
            r"
fn main() {
    // Fix$0
    // me
    let x = 1 + 1;
}
",
            r"
fn main() {
    // Fix
    // $0
    // me
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn does_not_continue_end_of_line_comment() {
        do_check_noop(
            r"
fn main() {
    // Fix me$0
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn continues_end_of_line_comment_with_space() {
        cov_mark::check!(continues_end_of_line_comment_with_space);
        do_check(
            r#"
fn main() {
    // Fix me $0
    let x = 1 + 1;
}
"#,
            r#"
fn main() {
    // Fix me
    // $0
    let x = 1 + 1;
}
"#,
        );
    }

    #[test]
    fn trims_all_trailing_whitespace() {
        do_check(
            "
fn main() {
    // Fix me  \t\t   $0
    let x = 1 + 1;
}
",
            "
fn main() {
    // Fix me
    // $0
    let x = 1 + 1;
}
",
        );
    }

    #[test]
    fn indents_fn_body_block() {
        cov_mark::check!(indent_block_contents);
        do_check(
            r#"
fn f() {$0()}
        "#,
            r#"
fn f() {
    $0()
}
        "#,
        );
    }

    #[test]
    fn indents_block_expr() {
        do_check(
            r#"
fn f() {
    let x = {$0()};
}
        "#,
            r#"
fn f() {
    let x = {
        $0()
    };
}
        "#,
        );
    }

    #[test]
    fn indents_match_arm() {
        do_check(
            r#"
fn f() {
    match 6 {
        1 => {$0f()},
        _ => (),
    }
}
        "#,
            r#"
fn f() {
    match 6 {
        1 => {
            $0f()
        },
        _ => (),
    }
}
        "#,
        );
    }

    #[test]
    fn indents_block_with_statement() {
        do_check(
            r#"
fn f() {$0a = b}
        "#,
            r#"
fn f() {
    $0a = b
}
        "#,
        );
        do_check(
            r#"
fn f() {$0fn f() {}}
        "#,
            r#"
fn f() {
    $0fn f() {}
}
        "#,
        );
    }

    #[test]
    fn indents_nested_blocks() {
        do_check(
            r#"
fn f() {$0{}}
        "#,
            r#"
fn f() {
    $0{}
}
        "#,
        );
    }

    #[test]
    fn does_not_indent_empty_block() {
        do_check_noop(
            r#"
fn f() {$0}
        "#,
        );
        do_check_noop(
            r#"
fn f() {{$0}}
        "#,
        );
    }

    #[test]
    fn does_not_indent_block_with_too_much_content() {
        do_check_noop(
            r#"
fn f() {$0 a = b; ()}
        "#,
        );
        do_check_noop(
            r#"
fn f() {$0 a = b; a = b; }
        "#,
        );
    }

    #[test]
    fn does_not_indent_multiline_block() {
        do_check_noop(
            r#"
fn f() {$0
}
        "#,
        );
        do_check_noop(
            r#"
fn f() {$0

}
        "#,
        );
    }

    #[test]
    fn indents_use_tree_list() {
        do_check(
            r#"
use crate::{$0};
            "#,
            r#"
use crate::{
    $0
};
            "#,
        );
        do_check(
            r#"
use crate::{$0Object, path::to::OtherThing};
            "#,
            r#"
use crate::{
    $0Object, path::to::OtherThing
};
            "#,
        );
        do_check(
            r#"
use {crate::{$0Object, path::to::OtherThing}};
            "#,
            r#"
use {crate::{
    $0Object, path::to::OtherThing
}};
            "#,
        );
        do_check(
            r#"
use {
    crate::{$0Object, path::to::OtherThing}
};
            "#,
            r#"
use {
    crate::{
        $0Object, path::to::OtherThing
    }
};
            "#,
        );
    }

    #[test]
    fn does_not_indent_use_tree_list_when_not_at_curly_brace() {
        do_check_noop(
            r#"
use path::{Thing$0};
            "#,
        );
    }

    #[test]
    fn does_not_indent_use_tree_list_without_curly_braces() {
        do_check_noop(
            r#"
use path::Thing$0;
            "#,
        );
        do_check_noop(
            r#"
use path::$0Thing;
            "#,
        );
        do_check_noop(
            r#"
use path::Thing$0};
            "#,
        );
        do_check_noop(
            r#"
use path::{$0Thing;
            "#,
        );
    }

    #[test]
    fn does_not_indent_multiline_use_tree_list() {
        do_check_noop(
            r#"
use path::{$0
    Thing
};
            "#,
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Add two missing commands<commit_after><|endoftext|>


<commit_before><commit_msg>Read to CRLF function added<commit_after><|endoftext|>


<commit_before><commit_msg>Add more context in error messages<commit_after><|endoftext|>


<commit_before><commit_msg>Prevent bot from talking to himself.<commit_after><|endoftext|>


<commit_before><commit_msg>feat: remove all unwrap<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>実行引数で使用するポートを指定できるように＋リファクタリング<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bug where a shootout was counted as a "Scheduled" game.<commit_after><|endoftext|>


<commit_before><commit_msg> Huh?<commit_after><|endoftext|>


<commit_before>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use rusoto::regions::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;

fn main() {
	let provider = DefaultAWSCredentialsProviderChain::new();
	let region = Region::UsEast1;

	let provider2 = ProfileCredentialsProvider::new();

	// Creates an SQS client with its own copy of the credential provider chain:
	let mut sqs = SQSHelper::new(provider2, &region);

	match sqs_roundtrip_tests(&mut sqs) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	// S3 client gets its own provider chain:
	let mut s3 = S3Helper::new(provider.clone(), &region);

	match s3_list_buckets_tests(&mut s3) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	let mut bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, None) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&mut s3, &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			match f.write(&(result.body)) {
				Err(why) => println!("Couldn't create file to save object from S3: {}", why),
				Ok(_) => (),
			}
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_put_object_with_reduced_redundancy_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object with reduced redundancy.");
		}
		Err(err) => { println!("Got error in s3 put object with reduced redundancy: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	println!("Making a large upload...");
	match s3_multipart_upload_test(&mut s3, &bucket_name) {
		Ok(_) => { println!("Everything worked for S3 multipart upload."); }
		Err(err) => { println!("Got error in s3 multipart upload: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "join.me.zip") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_list_multipart_uploads(&mut s3, &bucket_name) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(_) => println!("yay listed."),
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}

	// new bucket for canned acl testing!
	bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, Some(CannedAcl::AuthenticatedRead)) {
		Ok(_) => { println!("Everything worked for S3 create bucket with ACL."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_multipart_uploads(s3: &mut S3Helper, bucket: &str) -> Result<(), AWSError> {
	match s3.list_multipart_uploads_for_bucket(bucket) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(result) => println!("in-progress multipart uploads: {:?}", result),
	}
	Ok(())
}

fn s3_list_buckets_tests(s3: &mut S3Helper) -> Result<(), AWSError> {
	let response = try!(s3.list_buckets());
	// println!("response is {:?}", response);
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(s3: &mut S3Helper, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let response = try!(s3.get_object(bucket, "sample-credentials"));
	// println!("get object response is {:?}", response);
	Ok(response)
}

fn s3_delete_object_test(s3: &mut S3Helper, bucket: &str, object_name: &str) -> Result<DeleteObjectOutput, AWSError> {
	let response = try!(s3.delete_object(bucket, object_name));
	// println!("delete object response is {:?}", response);
	Ok(response)
}

fn s3_put_object_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents : Vec<u8> = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_multipart_upload_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("/Users/matthewmayer/Downloads/join.me.zip").unwrap();

	let response = try!(s3.put_multipart_object(bucket, "join.me.zip", &mut f));
	Ok(response)
}

fn s3_put_object_with_reduced_redundancy_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object_with_reduced_redundancy(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_create_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region, canned_acl: Option<CannedAcl>) -> Result<(), AWSError> {
	try!(s3.create_bucket_in_region(bucket, &region, canned_acl));

	Ok(())
}

fn s3_delete_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region) -> Result<(), AWSError> {
	try!(s3.delete_bucket(bucket, &region));
	Ok(())
}

fn sqs_roundtrip_tests(sqs: &mut SQSHelper) -> Result<(), AWSError> {
	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<commit_msg>Removes hardcoded file location that worked only on Matthew's machine.<commit_after>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use rusoto::regions::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;

fn main() {
	let provider = DefaultAWSCredentialsProviderChain::new();
	let region = Region::UsEast1;

	let provider2 = ProfileCredentialsProvider::new();

	// Creates an SQS client with its own copy of the credential provider chain:
	let mut sqs = SQSHelper::new(provider2, &region);

	match sqs_roundtrip_tests(&mut sqs) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	// S3 client gets its own provider chain:
	let mut s3 = S3Helper::new(provider.clone(), &region);

	match s3_list_buckets_tests(&mut s3) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	let mut bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, None) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&mut s3, &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			match f.write(&(result.body)) {
				Err(why) => println!("Couldn't create file to save object from S3: {}", why),
				Ok(_) => (),
			}
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_put_object_with_reduced_redundancy_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object with reduced redundancy.");
		}
		Err(err) => { println!("Got error in s3 put object with reduced redundancy: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	// Set the file in s3_multipart_upload_test and uncomment this code to test multipart upload:
	// println!("Making a large upload...");
	// match s3_multipart_upload_test(&mut s3, &bucket_name) {
	// 	Ok(_) => { println!("Everything worked for S3 multipart upload."); }
	// 	Err(err) => { println!("Got error in s3 multipart upload: {:#?}", err); }
	// }

	match s3_delete_object_test(&mut s3, &bucket_name, "join.me.zip") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_list_multipart_uploads(&mut s3, &bucket_name) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(_) => println!("yay listed."),
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}

	// new bucket for canned acl testing!
	bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, Some(CannedAcl::AuthenticatedRead)) {
		Ok(_) => { println!("Everything worked for S3 create bucket with ACL."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_multipart_uploads(s3: &mut S3Helper, bucket: &str) -> Result<(), AWSError> {
	match s3.list_multipart_uploads_for_bucket(bucket) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(result) => println!("in-progress multipart uploads: {:?}", result),
	}
	Ok(())
}

fn s3_list_buckets_tests(s3: &mut S3Helper) -> Result<(), AWSError> {
	let response = try!(s3.list_buckets());
	// println!("response is {:?}", response);
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(s3: &mut S3Helper, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let response = try!(s3.get_object(bucket, "sample-credentials"));
	Ok(response)
}

fn s3_delete_object_test(s3: &mut S3Helper, bucket: &str, object_name: &str) -> Result<DeleteObjectOutput, AWSError> {
	let response = try!(s3.delete_object(bucket, object_name));
	Ok(response)
}

fn s3_put_object_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents : Vec<u8> = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

// uncomment for multipart upload testing:
// fn s3_multipart_upload_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	// Set to a > 5 MB file for testing:
	// let mut f = File::open("/Users/matthewmayer/Downloads/join.me.zip").unwrap();
	//
	// let response = try!(s3.put_multipart_object(bucket, "join.me.zip", &mut f));
	// Ok(response)
// }

fn s3_put_object_with_reduced_redundancy_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object_with_reduced_redundancy(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_create_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region, canned_acl: Option<CannedAcl>) -> Result<(), AWSError> {
	try!(s3.create_bucket_in_region(bucket, &region, canned_acl));

	Ok(())
}

fn s3_delete_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region) -> Result<(), AWSError> {
	try!(s3.delete_bucket(bucket, &region));
	Ok(())
}

fn sqs_roundtrip_tests(sqs: &mut SQSHelper) -> Result<(), AWSError> {
	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use rusoto::regions::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;

fn main() {
	let provider = DefaultAWSCredentialsProviderChain::new();
	let region = Region::UsEast1;

	let provider2 = ProfileCredentialsProvider::new();

	// Creates an SQS client with its own copy of the credential provider chain:
	let mut sqs = SQSHelper::new(provider2, &region);

	match sqs_roundtrip_tests(&mut sqs) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	// S3 client gets its own provider chain:
	let mut s3 = S3Helper::new(provider.clone(), &region);

	match s3_list_buckets_tests(&mut s3) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	let mut bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, None) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&mut s3, &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			match f.write(&(result.body)) {
				Err(why) => println!("Couldn't create file to save object from S3: {}", why),
				Ok(_) => (),
			}
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_put_object_with_reduced_redundancy_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object with reduced redundancy.");
		}
		Err(err) => { println!("Got error in s3 put object with reduced redundancy: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	// Set the file in s3_multipart_upload_test and uncomment this code to test multipart upload:
	// println!("Making a large upload...");
	// match s3_multipart_upload_test(&mut s3, &bucket_name) {
	// 	Ok(_) => { println!("Everything worked for S3 multipart upload."); }
	// 	Err(err) => { println!("Got error in s3 multipart upload: {:#?}", err); }
	// }

	match s3_delete_object_test(&mut s3, &bucket_name, "join.me.zip") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_list_multipart_uploads(&mut s3, &bucket_name) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(_) => println!("yay listed."),
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}

	// new bucket for canned acl testing!
	bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, Some(CannedAcl::AuthenticatedRead)) {
		Ok(_) => { println!("Everything worked for S3 create bucket with ACL."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_multipart_uploads(s3: &mut S3Helper, bucket: &str) -> Result<(), AWSError> {
	match s3.list_multipart_uploads_for_bucket(bucket) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(result) => println!("in-progress multipart uploads: {:?}", result),
	}
	Ok(())
}

fn s3_list_buckets_tests(s3: &mut S3Helper) -> Result<(), AWSError> {
	let response = try!(s3.list_buckets());
	// println!("response is {:?}", response);
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(s3: &mut S3Helper, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let response = try!(s3.get_object(bucket, "sample-credentials"));
	Ok(response)
}

fn s3_delete_object_test(s3: &mut S3Helper, bucket: &str, object_name: &str) -> Result<DeleteObjectOutput, AWSError> {
	let response = try!(s3.delete_object(bucket, object_name));
	Ok(response)
}

fn s3_put_object_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents : Vec<u8> = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

// uncomment for multipart upload testing:
// fn s3_multipart_upload_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	// Set to a > 5 MB file for testing:
	// let mut f = File::open("/Users/matthewmayer/Downloads/join.me.zip").unwrap();
	//
	// let response = try!(s3.put_multipart_object(bucket, "join.me.zip", &mut f));
	// Ok(response)
// }

fn s3_put_object_with_reduced_redundancy_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object_with_reduced_redundancy(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_create_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region, canned_acl: Option<CannedAcl>) -> Result<(), AWSError> {
	try!(s3.create_bucket_in_region(bucket, &region, canned_acl));

	Ok(())
}

fn s3_delete_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region) -> Result<(), AWSError> {
	try!(s3.delete_bucket(bucket, &region));
	Ok(())
}

fn sqs_roundtrip_tests(sqs: &mut SQSHelper) -> Result<(), AWSError> {
	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<commit_msg>Fixes up S3 abort multipart upload.<commit_after>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use rusoto::regions::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;

fn main() {
	let provider = DefaultAWSCredentialsProviderChain::new();
	let region = Region::UsEast1;

	let provider2 = ProfileCredentialsProvider::new();

	// Creates an SQS client with its own copy of the credential provider chain:
	let mut sqs = SQSHelper::new(provider2, &region);

	match sqs_roundtrip_tests(&mut sqs) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	// S3 client gets its own provider chain:
	let mut s3 = S3Helper::new(provider.clone(), &region);

	match s3_list_buckets_tests(&mut s3) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	let mut bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, None) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&mut s3, &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			match f.write(&(result.body)) {
				Err(why) => println!("Couldn't create file to save object from S3: {}", why),
				Ok(_) => (),
			}
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_put_object_with_reduced_redundancy_test(&mut s3, &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object with reduced redundancy.");
		}
		Err(err) => { println!("Got error in s3 put object with reduced redundancy: {:#?}", err); }
	}

	match s3_delete_object_test(&mut s3, &bucket_name, "sample-credentials") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	// Set the file in s3_multipart_upload_test and uncomment this code to test multipart upload:
	// println!("Making a large upload...");
	// match s3_multipart_upload_test(&mut s3, &bucket_name) {
	// 	Ok(_) => { println!("Everything worked for S3 multipart upload."); }
	// 	Err(err) => { println!("Got error in s3 multipart upload: {:#?}", err); }
	// }

	match s3_delete_object_test(&mut s3, &bucket_name, "join.me.zip") {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_list_multipart_uploads(&mut s3, &bucket_name) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(_) => (),
	}

	// Working example, replace bucket name, file name, uploadID for your multipart upload:
	// match s3_abort_multipart_uploads(&mut s3, &bucket_name, "testfile.zip", "W5J7SeEor1A3vcRMMUhAb.BKrMs68.suzyhErssdb2HFAyDb4z7QhJBMyGkM_GSsoFqKJJLjbHcNSZTHa7MhTFJodewzcswshoDHd7mffXPNUH.xoRWVXbkLjakTETaO") {
	// 	Err(why) => println!("Error aborting multipart uploads: {:?}", why),
	// 	Ok(_) => (),
	// }

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}

	// new bucket for canned acl testing!
	bucket_name = format!("rusoto{}", get_time().sec);

	match s3_create_bucket_test(&mut s3, &bucket_name, &region, Some(CannedAcl::AuthenticatedRead)) {
		Ok(_) => { println!("Everything worked for S3 create bucket with ACL."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_delete_bucket_test(&mut s3, &bucket_name, &region) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_multipart_uploads(s3: &mut S3Helper, bucket: &str) -> Result<(), AWSError> {
	match s3.list_multipart_uploads_for_bucket(bucket) {
		Err(why) => println!("Error listing multipart uploads: {:?}", why),
		Ok(result) => println!("in-progress multipart uploads: {:?}", result),
	}
	Ok(())
}

fn s3_abort_multipart_uploads(s3: &mut S3Helper, bucket: &str, object: &str, upload_id: &str) -> Result<(), AWSError> {
	match s3.abort_multipart_upload(bucket, object, upload_id) {
		Err(why) => println!("Error aborting multipart upload: {:?}", why),
		Ok(result) => println!("aborted multipart upload: {:?}", result),
	}
	Ok(())
}

fn s3_list_buckets_tests(s3: &mut S3Helper) -> Result<(), AWSError> {
	let response = try!(s3.list_buckets());
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(s3: &mut S3Helper, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let response = try!(s3.get_object(bucket, "sample-credentials"));
	Ok(response)
}

fn s3_delete_object_test(s3: &mut S3Helper, bucket: &str, object_name: &str) -> Result<DeleteObjectOutput, AWSError> {
	let response = try!(s3.delete_object(bucket, object_name));
	Ok(response)
}

fn s3_put_object_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents : Vec<u8> = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

// uncomment for multipart upload testing:
fn s3_multipart_upload_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	// Set to a > 5 MB file for testing:
	let mut f = File::open("testfile.zip").unwrap();

	let response = try!(s3.put_multipart_object(bucket, "testfile.zip", &mut f));
	Ok(response)
}

fn s3_put_object_with_reduced_redundancy_test(s3: &mut S3Helper, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object_with_reduced_redundancy(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_create_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region, canned_acl: Option<CannedAcl>) -> Result<(), AWSError> {
	try!(s3.create_bucket_in_region(bucket, &region, canned_acl));

	Ok(())
}

fn s3_delete_bucket_test(s3: &mut S3Helper, bucket: &str, region: &Region) -> Result<(), AWSError> {
	try!(s3.delete_bucket(bucket, &region));
	Ok(())
}

fn sqs_roundtrip_tests(sqs: &mut SQSHelper) -> Result<(), AWSError> {
	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<|endoftext|>


<commit_before>extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate sprite;

use piston_window::{ PistonWindow, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
use graphics::*;

mod app;

pub struct Size {
    width: u32,
    height: u32
}

impl ImageSize for Size {
    fn get_size(&self) -> (u32, u32) {
        return (self.width, self.height);
    }
}

fn main() {
    let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
        .exit_on_esc(true)
        .build()
        .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) });
    window.set_ups(60);

    let mut app = app::App::new();

    for e in window {
        if let Some(args) = e.render_args() {
            app.render(args);
        }

        if let Some(args) = e.update_args() {
            app.update(args);
        }

        if let Some(args) = e.press_args() {
            app.key_press(args);
        }
    }
}
<commit_msg>Added struct for position.<commit_after>extern crate piston;
extern crate graphics;
extern crate piston_window;
extern crate time;
extern crate rand;
extern crate ai_behavior;
extern crate sprite;

use piston_window::{ PistonWindow, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
use graphics::*;

mod app;

pub struct Position {
    x: f32,
    y: f32
}

pub struct Size {
    width: u32,
    height: u32
}

impl ImageSize for Size {
    fn get_size(&self) -> (u32, u32) {
        return (self.width, self.height);
    }
}

fn main() {
    let mut window: PistonWindow = WindowSettings::new("GGJ2016", [800, 600])
        .exit_on_esc(true)
        .build()
        .unwrap_or_else(|e| { panic!("Failed to build PistonWindow: {}", e) });
    window.set_ups(60);

    let mut app = app::App::new();

    for e in window {
        if let Some(args) = e.render_args() {
            app.render(args);
        }

        if let Some(args) = e.update_args() {
            app.update(args);
        }

        if let Some(args) = e.press_args() {
            app.key_press(args);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add celsius conversion and factor out weather retrieval<commit_after><|endoftext|>


<commit_before><commit_msg>minor changes<commit_after><|endoftext|>


<commit_before><commit_msg>Use hyper_tls for requests instead of tokio_tls<commit_after><|endoftext|>


<commit_before><commit_msg>Fix(util): if the hostname env var is blank, fall back to OS hostname<commit_after><|endoftext|>


<commit_before><commit_msg>Disable history file by default (until Redox is better with write support)<commit_after><|endoftext|>


<commit_before><commit_msg>Very simple, crappy, partial solver<commit_after><|endoftext|>


<commit_before><commit_msg>:sparkles: Add the feature of sending to Slack<commit_after><|endoftext|>


<commit_before><commit_msg>Panic with a message when threshold value cannot be parsed<commit_after><|endoftext|>


<commit_before><commit_msg>Fix missing files<commit_after>use flow::Flow;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

type SharedFlow = Arc<RwLock<Flow>>;

pub struct Pool {
    bucket: HashMap<String, SharedFlow>,
}

impl Pool {
    pub fn new() -> Arc<RwLock<Self>> {
        let pool = Pool { bucket: HashMap::new() };
        Arc::new(RwLock::new(pool))
    }

    pub fn insert(&mut self, flow_id: &str, flow_ptr: SharedFlow) {
        self.bucket.insert(flow_id.to_owned(), flow_ptr);
    }

    pub fn get(&self, flow_id: &str) -> Option<SharedFlow> {
        self.bucket.get(flow_id).map(|flow_ptr| flow_ptr.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use flow::Flow;
    use std::sync::Arc;

    #[test]
    fn basic_operations() {
        let ptr = Pool::new();
        let flow_a = Flow::new(None);
        let flow_b = Flow::new(None);

        {
            let mut pool = ptr.write().unwrap();
            pool.insert("A", flow_a.clone());
            pool.insert("B", flow_b.clone());
        }

        {
            let pool = ptr.read().unwrap();
            assert!(Arc::ptr_eq(&pool.get("A").unwrap(), &flow_a));
            assert!(Arc::ptr_eq(&pool.get("B").unwrap(), &flow_b));
            assert!(!Arc::ptr_eq(&pool.get("A").unwrap(), &flow_b));
            assert!(!Arc::ptr_eq(&pool.get("B").unwrap(), &flow_a));
            assert!(!pool.get("C").is_some());
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>cleaned up more numeric conversions<commit_after><|endoftext|>