<commit_before>#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results, unused_typecasts)]

#![feature(exit_status, io, old_io, os, path, process, std_misc)]

extern crate glob;
extern crate "rustc-serialize" as rustc_serialize;
extern crate term;
extern crate common;

use std::borrow::{Cow, IntoCow};
use std::env;
use std::error::FromError;
use std::io;
use std::old_io;
use std::path::Path;
use std::process::Command;
use std::str;
use std::os::unix::ExitStatusExt;
use glob::Paths;
use rustc_serialize::Decodable;
use rustc_serialize::json::{self, Json};
use term::color::Color;
use common::SolverResult;

const PROBLEM_EXE_PAT: &'static str = "p[0-9][0-9][0-9]";

type ProgramResult<T> = Result<T, ProgramError>;
type OutputPair<'a> = (Option<Color>, Cow<'a, str>);

#[derive(Debug)]
enum ProgramError {
    IoError(io::Error),
    OldIoError(old_io::IoError),
    JsonParserError(json::ParserError),
    JsonDecoderError(json::DecoderError),
    Unknown(Cow<'static, str>)
}

impl ProgramError {
    fn unknown<T: IntoCow<'static, str>>(msg: T) -> ProgramError {
        ProgramError::Unknown(msg.into_cow())
    }
}

impl FromError<io::Error> for ProgramError {
    fn from_error(err: io::Error) -> ProgramError {
        ProgramError::IoError(err)
    }
}

impl FromError<old_io::IoError> for ProgramError {
    fn from_error(err: old_io::IoError) -> ProgramError {
        ProgramError::OldIoError(err)
    }
}

impl FromError<json::ParserError> for ProgramError {
    fn from_error(err: json::ParserError) -> ProgramError {
        ProgramError::JsonParserError(err)
    }
}

impl FromError<json::DecoderError> for ProgramError {
    fn from_error(err: json::DecoderError) -> ProgramError {
        ProgramError::JsonDecoderError(err)
    }
}

fn problem_paths(dir_path: &Path) -> ProgramResult<Paths> {
    let pat = dir_path.join(PROBLEM_EXE_PAT);
    match pat.to_str() {
        Some(x) => Ok(glob::glob(x).unwrap()),
        None    => Err(ProgramError::unknown("path contains non-utf8 character"))
    }
}

fn run_problem(path: &Path) -> ProgramResult<SolverResult<String>> {
    let proc_out = try!(Command::new(path).arg("--json").output());

    if !proc_out.stderr.is_empty() {
        let _ = match str::from_utf8(&proc_out.stderr) {
            Ok(s)  => writeln!(&mut old_io::stderr(), "{}", s.trim()),
            Err(e) => writeln!(&mut old_io::stderr(), "{:?}: {}", proc_out.stderr, e)
        };
    }

    match proc_out.status.code() {
        Some(0) | Some(1) => {} // expected
        Some(st) => {
            return Err(ProgramError::unknown(format!("child process exit with {}", st)))
        }
        None => {
            return Err(ProgramError::unknown(format!("child process exit with siglan {}", proc_out.status.signal().unwrap())))
        }
    }

    let json = try!(Json::from_reader(&mut &proc_out.stdout[..]));
    Ok(try!(Decodable::decode(&mut json::Decoder::new(json))))
}

fn run() -> ProgramResult<()> {
    let dir_path = {
        let mut path = try!(env::current_exe());
        path.pop();
        path
    };
    let mut out = old_io::stdout();

    let mut is_ok = true;
    let mut num_prob = 0;
    let mut total_time = 0;
    for path in try!(problem_paths(&dir_path)) {
        let path = path.unwrap();
        let program = path.file_name().unwrap().to_string_lossy().to_string();

        match run_problem(&path) {
            Ok(ref r) => {
                num_prob   += 1;
                total_time += r.time;
                is_ok &= r.is_ok;
                let _ = r.print_pretty(&program, true);
            }
            Err(e) => {
                is_ok = false;
                let _ = writeln!(&mut out, "{}: {:?}", program, e);
            }
        }
    }

    if num_prob > 0 {
        let r = SolverResult {
            time: total_time / num_prob,
            answer: "".to_string(),
            is_ok: is_ok
        };
        let _ = r.print_pretty(" AVG", true);

        let r = SolverResult {
            time: total_time,
            answer: "".to_string(),
            is_ok: is_ok
        };
        let _ = r.print_pretty(" SUM", false);
    }

    if !is_ok {
        env::set_exit_status(1);
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        let _ = writeln!(&mut old_io::stderr(), "{:?}", e);
        env::set_exit_status(255);
    }
}
<commit_msg>euler: remove old_io<commit_after>#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results, unused_typecasts)]

#![feature(exit_status, io, os, path, std_misc)]

extern crate glob;
extern crate "rustc-serialize" as rustc_serialize;
extern crate term;
extern crate common;

use std::borrow::{Cow, IntoCow};
use std::env;
use std::error::FromError;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::process::Command;
use std::str;
use std::os::unix::ExitStatusExt;
use glob::Paths;
use rustc_serialize::Decodable;
use rustc_serialize::json::{self, Json};
use term::color::Color;
use common::SolverResult;

const PROBLEM_EXE_PAT: &'static str = "p[0-9][0-9][0-9]";

type ProgramResult<T> = Result<T, ProgramError>;
type OutputPair<'a> = (Option<Color>, Cow<'a, str>);

#[derive(Debug)]
enum ProgramError {
    IoError(io::Error),
    JsonParserError(json::ParserError),
    JsonDecoderError(json::DecoderError),
    Unknown(Cow<'static, str>)
}

impl ProgramError {
    fn unknown<T: IntoCow<'static, str>>(msg: T) -> ProgramError {
        ProgramError::Unknown(msg.into_cow())
    }
}

impl FromError<io::Error> for ProgramError {
    fn from_error(err: io::Error) -> ProgramError {
        ProgramError::IoError(err)
    }
}

impl FromError<json::ParserError> for ProgramError {
    fn from_error(err: json::ParserError) -> ProgramError {
        ProgramError::JsonParserError(err)
    }
}

impl FromError<json::DecoderError> for ProgramError {
    fn from_error(err: json::DecoderError) -> ProgramError {
        ProgramError::JsonDecoderError(err)
    }
}

fn problem_paths(dir_path: &Path) -> ProgramResult<Paths> {
    let pat = dir_path.join(PROBLEM_EXE_PAT);
    match pat.to_str() {
        Some(x) => Ok(glob::glob(x).unwrap()),
        None    => Err(ProgramError::unknown("path contains non-utf8 character"))
    }
}

fn run_problem(path: &Path) -> ProgramResult<SolverResult<String>> {
    let proc_out = try!(Command::new(path).arg("--json").output());

    if !proc_out.stderr.is_empty() {
        let _ = match str::from_utf8(&proc_out.stderr) {
            Ok(s)  => writeln!(&mut io::stderr(), "{}", s.trim()),
            Err(e) => writeln!(&mut io::stderr(), "{:?}: {}", proc_out.stderr, e)
        };
    }

    match proc_out.status.code() {
        Some(0) | Some(1) => {} // expected
        Some(st) => {
            return Err(ProgramError::unknown(format!("child process exit with {}", st)))
        }
        None => {
            return Err(ProgramError::unknown(format!("child process exit with siglan {}", proc_out.status.signal().unwrap())))
        }
    }

    let json = try!(Json::from_reader(&mut &proc_out.stdout[..]));
    Ok(try!(Decodable::decode(&mut json::Decoder::new(json))))
}

fn run() -> ProgramResult<()> {
    let dir_path = {
        let mut path = try!(env::current_exe());
        path.pop();
        path
    };
    let mut out = io::stdout();

    let mut is_ok = true;
    let mut num_prob = 0;
    let mut total_time = 0;
    for path in try!(problem_paths(&dir_path)) {
        let path = path.unwrap();
        let program = path.file_name().unwrap().to_string_lossy().to_string();

        match run_problem(&path) {
            Ok(ref r) => {
                num_prob   += 1;
                total_time += r.time;
                is_ok &= r.is_ok;
                let _ = r.print_pretty(&program, true);
            }
            Err(e) => {
                is_ok = false;
                let _ = writeln!(&mut out, "{}: {:?}", program, e);
            }
        }
    }

    if num_prob > 0 {
        let r = SolverResult {
            time: total_time / num_prob,
            answer: "".to_string(),
            is_ok: is_ok
        };
        let _ = r.print_pretty(" AVG", true);

        let r = SolverResult {
            time: total_time,
            answer: "".to_string(),
            is_ok: is_ok
        };
        let _ = r.print_pretty(" SUM", false);
    }

    if !is_ok {
        env::set_exit_status(1);
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        let _ = writeln!(&mut io::stderr(), "{:?}", e);
        env::set_exit_status(255);
    }
}
<|endoftext|>


<commit_before>extern crate frappe;
#[macro_use]
extern crate log;
extern crate env_logger;

use std::fs::File;

use frappe::classfile::reader::ClassReader;
use frappe::javap::{Disassemble, Formatter, Options};

fn main() {
    env_logger::init().unwrap();
    let verbose = true;
    let classname = "io.hcf.frappe.HelloWorld";
    let mut class_filename = classname.replace('.', "/");
    class_filename.push_str(".class");
    let class_file = File::open(class_filename).unwrap();
    let mut fmt = Formatter::new();
    let class = ClassReader::new(class_file).read_class().unwrap();
    let opts = Options {
        verbose: verbose,
        constants: &class.constants,
    };
    class.pretty_print(&mut fmt, &opts).unwrap();
}
<commit_msg>Remove hard-coded classfile from javap.<commit_after>extern crate frappe;
#[macro_use]
extern crate log;
extern crate env_logger;

use std::fs::File;
use std::env;

use frappe::classfile::reader::ClassReader;
use frappe::javap::{Disassemble, Formatter, Options};

fn main() {
    env_logger::init().unwrap();
    let verbose = true;
    let class_filename = env::args().nth(1).expect("usage: class_reader <class file>");
    let class_file = File::open(class_filename).unwrap();
    let mut fmt = Formatter::new();
    let class = ClassReader::new(class_file).read_class().unwrap();
    let opts = Options {
        verbose: verbose,
        constants: &class.constants,
    };
    class.pretty_print(&mut fmt, &opts).unwrap();
}
<|endoftext|>


<commit_before>extern crate argparse;
extern crate image;
extern crate path_tracer;

use argparse::{ArgumentParser, Store, Collect};
use path_tracer::*;
use std::fs::File;
use std::io::{self, BufReader};
use std::io::prelude::*;

struct PartialImage {
    image : Vec<Vec<Vec3d>>,
    samples : i32,
}

impl PartialImage {
    fn empty() -> PartialImage {
        PartialImage { image: Vec::new(), samples: 0 }
    }

    // I'm totally unsure about whether this is taking additional copies.
    fn add(self, other: PartialImage) -> PartialImage {
        let image = if self.samples == 0 { other.image } else {
            // A nicer way to do this would be ideal. This may well be doing lots of boundchecks.
            let mut combined : Vec<Vec<Vec3d>> = self.image;
            for y in 0..combined.len() {
                for x in 0..combined[y].len() {
                    combined[y][x] = combined[y][x] + other.image[y][x];
                }
            }
            combined
        };
        let samples = self.samples + other.samples;
        PartialImage { image: image, samples: samples }
    }

    fn height(&self) -> usize {
        self.image.len()
    }
    fn width(&self) -> usize {
        self.image[0].len()
    }
}

fn load_file(name: &String) -> io::Result<PartialImage> {
    let mut result : Vec<Vec<Vec3d>> = Vec::new();
    let file = BufReader::new(try!(File::open(&name)));
    println!("Loading '{}'", name);
    let mut line_iter = file.lines();
    let first_line = line_iter.next().unwrap().ok().unwrap();
    let mut first_line_words = first_line.split(' ').map(|x| x.parse::<i32>().unwrap());
    let width = first_line_words.next().unwrap() as usize;
    let height = first_line_words.next().unwrap() as usize;
    let samples = first_line_words.next().unwrap(); // this is terrible
    println!("Found {} samples in {}x{} image", samples, width, height);
    for line in line_iter.filter_map(|x| x.ok()) {
        let mut vecs : Vec<Vec3d> = Vec::new();
        let mut split = line.split(' ').map(|x| x.parse::<f64>().unwrap());
        loop {
            let x = match split.next() {
                None => break,
                Some(x) => x
            };
            let y : f64 = split.next().unwrap();
            let z : f64 = split.next().unwrap();
            vecs.push(Vec3d::new(x, y, z) * samples as f64);
        }
        if vecs.len() != width {
            panic!("bad width"); // todo
            //return Err("Bad width");
        }
        result.push(vecs);
    }
    if result.len() != height {
        panic!("bad height"); // todo
        //return Err("Bad height");
    }
    println!("Loaded ok");
    Ok(PartialImage { image: result, samples: samples })
}

fn main() {
    let mut to_merge : Vec<String> = Vec::new();
    let mut output_filename = "image.png".to_string();
    {
        let mut ap = ArgumentParser::new();
        ap.set_description("Combine several sample images into one PNG");
        ap.refer(&mut output_filename).add_option(&["-o", "--output"], Store,
                                                  "Filename to output to");
        ap.refer(&mut to_merge).add_argument("files", Collect, "Files to merge")
            .required();
        ap.parse_args_or_exit();
    }
    let accum : PartialImage = to_merge.iter()
        .map(load_file)
        .map(|x| x.unwrap())
        .fold(PartialImage::empty(), |acc, item| { acc.add(item) });

    println!("Merged {} samples", accum.samples);
    println!("Writing output to '{}'", output_filename);
    let height = accum.height();
    let width = accum.width();
    let samples = accum.samples;
    let mut image = image::ImageBuffer::new(width as u32, height as u32);
    for y in 0..height {
        for x in 0..width {
            let sum = accum.image[y][x] / samples as f64;
            image.put_pixel(x as u32, y as u32, image::Rgb([to_int(sum.x), to_int(sum.y), to_int(sum.z)]));
        }
    }
    let mut output_file = File::create(output_filename).unwrap();
    image::ImageRgb8(image).save(&mut output_file, image::PNG).unwrap();
}
<commit_msg>Handle errors more Rustfully<commit_after>extern crate argparse;
extern crate image;
extern crate path_tracer;

use argparse::{ArgumentParser, Store, Collect};
use path_tracer::*;
use std::fs::File;
use std::io::{self, BufReader};
use std::io::prelude::*;

#[derive(Debug)]
enum ImageError {
    IoError(io::Error),
    BadFileError(String)
}
use ImageError::*;

impl From<io::Error> for ImageError {
    fn from(e: io::Error) -> ImageError {
        ImageError::IoError(e)
    }
}
type Result<T> = std::result::Result<T, ImageError>;

struct PartialImage {
    image : Vec<Vec<Vec3d>>,
    samples : i32,
}

impl PartialImage {
    fn empty() -> PartialImage {
        PartialImage { image: Vec::new(), samples: 0 }
    }

    // I'm totally unsure about whether this is taking additional copies.
    fn add(self, other: PartialImage) -> PartialImage {
        let image = if self.samples == 0 { other.image } else {
            // A nicer way to do this would be ideal. This may well be doing lots of boundchecks.
            let mut combined : Vec<Vec<Vec3d>> = self.image;
            for y in 0..combined.len() {
                for x in 0..combined[y].len() {
                    combined[y][x] = combined[y][x] + other.image[y][x];
                }
            }
            combined
        };
        let samples = self.samples + other.samples;
        PartialImage { image: image, samples: samples }
    }

    fn height(&self) -> usize {
        self.image.len()
    }
    fn width(&self) -> usize {
        self.image[0].len()
    }
}

fn load_file(name: &String) -> Result<PartialImage> {
    let mut result : Vec<Vec<Vec3d>> = Vec::new();
    let file = BufReader::new(try!(File::open(&name)));
    println!("Loading '{}'", name);
    let mut line_iter = file.lines();
    let first_line = line_iter.next().unwrap().ok().unwrap();
    let mut first_line_words = first_line.split(' ').map(|x| x.parse::<i32>().unwrap());
    let width = first_line_words.next().unwrap() as usize;
    let height = first_line_words.next().unwrap() as usize;
    let samples = first_line_words.next().unwrap(); // this is terrible
    println!("Found {} samples in {}x{} image", samples, width, height);
    for line in line_iter.filter_map(|x| x.ok()) {
        let mut vecs : Vec<Vec3d> = Vec::new();
        let mut split = line.split(' ').map(|x| x.parse::<f64>().unwrap());
        loop {
            let x = match split.next() {
                None => break,
                Some(x) => x
            };
            let y : f64 = split.next().unwrap();
            let z : f64 = split.next().unwrap();
            vecs.push(Vec3d::new(x, y, z) * samples as f64);
        }
        if vecs.len() != width {
            return Err(BadFileError("Bad width".to_string()));
        }
        result.push(vecs);
    }
    if result.len() != height {
        return Err(BadFileError("Bad height".to_string()));
    }
    println!("Loaded ok");
    Ok(PartialImage { image: result, samples: samples })
}

fn main() {
    let mut to_merge : Vec<String> = Vec::new();
    let mut output_filename = "image.png".to_string();
    {
        let mut ap = ArgumentParser::new();
        ap.set_description("Combine several sample images into one PNG");
        ap.refer(&mut output_filename).add_option(&["-o", "--output"], Store,
                                                  "Filename to output to");
        ap.refer(&mut to_merge).add_argument("files", Collect, "Files to merge")
            .required();
        ap.parse_args_or_exit();
    }
    let accum : PartialImage = to_merge.iter()
        .map(load_file)
        .map(|x| x.unwrap())
        .fold(PartialImage::empty(), |acc, item| { acc.add(item) });

    println!("Merged {} samples", accum.samples);
    println!("Writing output to '{}'", output_filename);
    let height = accum.height();
    let width = accum.width();
    let samples = accum.samples;
    let mut image = image::ImageBuffer::new(width as u32, height as u32);
    for y in 0..height {
        for x in 0..width {
            let sum = accum.image[y][x] / samples as f64;
            image.put_pixel(x as u32, y as u32, image::Rgb([to_int(sum.x), to_int(sum.y), to_int(sum.z)]));
        }
    }
    let mut output_file = File::create(output_filename).unwrap();
    image::ImageRgb8(image).save(&mut output_file, image::PNG).unwrap();
}
<|endoftext|>


<commit_before>use gl;
use std::default::Default;
use std::os::raw::c_void;
use std::sync::mpsc;
use std::thread;

pub use glfw::{self, Action, Context, CursorMode, Key, MouseButton, Window};

#[derive(Clone, Copy, Debug)]
pub enum LuminanceBackend {
  GL33
}

impl Default for LuminanceBackend {
  fn default() -> Self {
    LuminanceBackend::GL33
  }
}

#[derive(Clone, Copy, Debug)]
pub enum WindowDim {
  Windowed(u32, u32),
  FullScreen,
  FullScreenRestricted(u32, u32)
}

pub type Keyboard = mpsc::Receiver<(Key, Action)>;
pub type Mouse = mpsc::Receiver<(MouseButton, Action)>;
pub type MouseMove = mpsc::Receiver<[f64; 2]>;
pub type Scroll = mpsc::Receiver<[f64; 2]>;

pub fn bootstrap<App: FnOnce(u32, u32, Keyboard, Mouse, MouseMove, Scroll, Window)>(dim: WindowDim, title: &'static str, backend: LuminanceBackend, app: App) {
  info!("{} starting", title);
  info!("window mode: {:?}", dim);
  info!("luminance backend: {:?}", backend);

  let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

  match backend {
    LuminanceBackend::GL33 => {
      // OpenGL hints; implements luminance-gl’s core contexts creation
      glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
      glfw.window_hint(glfw::WindowHint::ContextVersionMajor(3));
      glfw.window_hint(glfw::WindowHint::ContextVersionMinor(3));
    }
  }

  // open a window in windowed or fullscreen mode
  let (mut window, events, w, h) = match dim {
    WindowDim::Windowed(w, h) => {
      let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::Windowed).expect("Failed to create GLFW window.");
      (window, events, w, h)
    },
    WindowDim::FullScreen => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();
        let vmode = monitor.get_video_mode().expect("primary monitor’s video mode");
        let (w, h) = (vmode.width, vmode.height);

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    },
    WindowDim::FullScreenRestricted(w, h) => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    }
  };

  deb!("opened window");

  window.make_current();

  if cfg!(feature = "release") {
    deb!("hiding cursor");
    window.set_cursor_mode(CursorMode::Disabled);
  }

  window.set_key_polling(true);
  window.set_cursor_pos_polling(true);
  window.set_mouse_button_polling(true);
  window.set_scroll_polling(true);

  deb!("initializing OpenGL pointers");

  // init OpenGL
  gl::load_with(|s| window.get_proc_address(s) as *const c_void);

  // create channels to stream keyboard and mouse events
  let (kbd_snd, kbd_rcv) = mpsc::channel();
  let (mouse_snd, mouse_rcv) = mpsc::channel();
  let (mouse_move_snd, mouse_move_rcv) = mpsc::channel();
  let (scroll_snd, scroll_rcv) = mpsc::channel();

  deb!("spawing the event thread");
  let _ = thread::spawn(move || {
    loop {
      glfw.wait_events();

      for (_, event) in glfw::flush_messages(&events) {
        match event {
            glfw::WindowEvent::Key(key, _, action, _) => {
              let _ = kbd_snd.send((key, action));
            },
            glfw::WindowEvent::MouseButton(button, action, _) => {
              let _ = mouse_snd.send((button, action));
            },
            glfw::WindowEvent::CursorPos(x, y) => {
              let _ = mouse_move_snd.send([x, y]);
            },
            glfw::WindowEvent::Scroll(x, y) => {
              let _ = scroll_snd.send([x, y]);
            },
            _ => {},
        }
      }
    }
  });

  deb!("bootstrapping finished");
  app(w, h, kbd_rcv, mouse_rcv, mouse_move_rcv, scroll_rcv, window);
}
<commit_msg>Typo.<commit_after>use gl;
use std::default::Default;
use std::os::raw::c_void;
use std::sync::mpsc;
use std::thread;

pub use glfw::{self, Action, Context, CursorMode, Key, MouseButton, Window};

#[derive(Clone, Copy, Debug)]
pub enum LuminanceBackend {
  GL33
}

impl Default for LuminanceBackend {
  fn default() -> Self {
    LuminanceBackend::GL33
  }
}

#[derive(Clone, Copy, Debug)]
pub enum WindowDim {
  Windowed(u32, u32),
  FullScreen,
  FullScreenRestricted(u32, u32)
}

pub type Keyboard = mpsc::Receiver<(Key, Action)>;
pub type Mouse = mpsc::Receiver<(MouseButton, Action)>;
pub type MouseMove = mpsc::Receiver<[f64; 2]>;
pub type Scroll = mpsc::Receiver<[f64; 2]>;

pub fn bootstrap<App: FnOnce(u32, u32, Keyboard, Mouse, MouseMove, Scroll, Window)>(dim: WindowDim, title: &'static str, backend: LuminanceBackend, app: App) {
  info!("{} starting", title);
  info!("window mode: {:?}", dim);
  info!("luminance backend: {:?}", backend);

  let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

  match backend {
    LuminanceBackend::GL33 => {
      // OpenGL hints; implements luminance-gl’s core contexts creation
      glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
      glfw.window_hint(glfw::WindowHint::ContextVersionMajor(3));
      glfw.window_hint(glfw::WindowHint::ContextVersionMinor(3));
    }
  }

  // open a window in windowed or fullscreen mode
  let (mut window, events, w, h) = match dim {
    WindowDim::Windowed(w, h) => {
      let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::Windowed).expect("Failed to create GLFW window.");
      (window, events, w, h)
    },
    WindowDim::FullScreen => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();
        let vmode = monitor.get_video_mode().expect("primary monitor’s video mode");
        let (w, h) = (vmode.width, vmode.height);

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    },
    WindowDim::FullScreenRestricted(w, h) => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    }
  };

  deb!("opened window");

  window.make_current();

  if cfg!(feature = "release") {
    deb!("hiding cursor");
    window.set_cursor_mode(CursorMode::Disabled);
  }

  window.set_key_polling(true);
  window.set_cursor_pos_polling(true);
  window.set_mouse_button_polling(true);
  window.set_scroll_polling(true);

  deb!("initializing OpenGL pointers");

  // init OpenGL
  gl::load_with(|s| window.get_proc_address(s) as *const c_void);

  // create channels to stream keyboard and mouse events
  let (kbd_snd, kbd_rcv) = mpsc::channel();
  let (mouse_snd, mouse_rcv) = mpsc::channel();
  let (mouse_move_snd, mouse_move_rcv) = mpsc::channel();
  let (scroll_snd, scroll_rcv) = mpsc::channel();

  deb!("spawning the event thread");
  let _ = thread::spawn(move || {
    loop {
      glfw.wait_events();

      for (_, event) in glfw::flush_messages(&events) {
        match event {
            glfw::WindowEvent::Key(key, _, action, _) => {
              let _ = kbd_snd.send((key, action));
            },
            glfw::WindowEvent::MouseButton(button, action, _) => {
              let _ = mouse_snd.send((button, action));
            },
            glfw::WindowEvent::CursorPos(x, y) => {
              let _ = mouse_move_snd.send([x, y]);
            },
            glfw::WindowEvent::Scroll(x, y) => {
              let _ = scroll_snd.send([x, y]);
            },
            _ => {},
        }
      }
    }
  });

  deb!("bootstrapping finished");
  app(w, h, kbd_rcv, mouse_rcv, mouse_move_rcv, scroll_rcv, window);
}
<|endoftext|>


<commit_before>use super::controls;

use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::mpsc::{SendError, Sender};

static GLOBAL_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct CallbackId(usize);

impl CallbackId {
    pub fn next() -> CallbackId {
        CallbackId(atomic_next())
    }
}

fn atomic_next() -> usize {
    GLOBAL_COUNT.fetch_add(1, Ordering::SeqCst)
}

pub trait Callback {
    fn name(&self) -> &'static str;
    fn id(&self) -> CallbackId;
}

#[derive(Debug, Clone)]
pub struct AsyncFeeder<T: Callback> {
    sender: Sender<T>,
}
impl<T: Callback> AsyncFeeder<T> {
    pub fn feed(&mut self, data: T) -> Result<(), SendError<T>> {
        self.sender.send(data)
    }
}
impl<T: Callback> From<Sender<T>> for AsyncFeeder<T> {
    fn from(s: Sender<T>) -> Self {
        AsyncFeeder { sender: s }
    }
}

#[macro_export]
macro_rules! callback {
	($id: ident, $($typ:tt)+) => {
		pub struct $id(CallbackId, Box<dyn $($typ)+>);

		impl Callback for $id {
			fn name(&self) -> &'static str {
				stringify!($id)
			}
			fn id(&self) -> CallbackId {
				self.0
			}
		}

		impl <T> From<T> for $id where T: $($typ)+ + Sized + 'static {
			fn from(t: T) -> $id {
				$id(CallbackId::next(), Box::new(t))
			}
		}
		impl AsRef<dyn $($typ)+> for $id {
			fn as_ref(&self) -> &(dyn $($typ)+  + 'static) {
				self.1.as_ref()
			}
		}
		impl AsMut<dyn $($typ)+> for $id {
			fn as_mut(&mut self) -> &mut (dyn $($typ)+ + 'static) {
				self.1.as_mut()
			}
		}
		impl From<$id> for (CallbackId, Box<dyn $($typ)+>) {
		    fn from(a: $id) -> Self {
		        (a.0, a.1)
		    }
		}
		impl From<(CallbackId, Box<dyn $($typ)+>)> for $id {
		    fn from(a: (CallbackId, Box<dyn $($typ)+>)) -> Self {
		        $id(a.0, a.1)
		    }
		}
	}
}

callback!(Resize, FnMut(&mut dyn controls::Member, u16, u16));
callback!(Click, FnMut(&mut dyn controls::Button));
callback!(Frame, FnMut(&mut dyn controls::Window) -> bool);
<commit_msg>Minor clickable fix<commit_after>use super::controls;

use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::mpsc::{SendError, Sender};

static GLOBAL_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct CallbackId(usize);

impl CallbackId {
    pub fn next() -> CallbackId {
        CallbackId(atomic_next())
    }
}

fn atomic_next() -> usize {
    GLOBAL_COUNT.fetch_add(1, Ordering::SeqCst)
}

pub trait Callback {
    fn name(&self) -> &'static str;
    fn id(&self) -> CallbackId;
}

#[derive(Debug, Clone)]
pub struct AsyncFeeder<T: Callback> {
    sender: Sender<T>,
}
impl<T: Callback> AsyncFeeder<T> {
    pub fn feed(&mut self, data: T) -> Result<(), SendError<T>> {
        self.sender.send(data)
    }
}
impl<T: Callback> From<Sender<T>> for AsyncFeeder<T> {
    fn from(s: Sender<T>) -> Self {
        AsyncFeeder { sender: s }
    }
}

#[macro_export]
macro_rules! callback {
	($id: ident, $($typ:tt)+) => {
		pub struct $id(CallbackId, Box<dyn $($typ)+>);

		impl Callback for $id {
			fn name(&self) -> &'static str {
				stringify!($id)
			}
			fn id(&self) -> CallbackId {
				self.0
			}
		}

		impl <T> From<T> for $id where T: $($typ)+ + Sized + 'static {
			fn from(t: T) -> $id {
				$id(CallbackId::next(), Box::new(t))
			}
		}
		impl AsRef<dyn $($typ)+> for $id {
			fn as_ref(&self) -> &(dyn $($typ)+  + 'static) {
				self.1.as_ref()
			}
		}
		impl AsMut<dyn $($typ)+> for $id {
			fn as_mut(&mut self) -> &mut (dyn $($typ)+ + 'static) {
				self.1.as_mut()
			}
		}
		impl From<$id> for (CallbackId, Box<dyn $($typ)+>) {
		    fn from(a: $id) -> Self {
		        (a.0, a.1)
		    }
		}
		impl From<(CallbackId, Box<dyn $($typ)+>)> for $id {
		    fn from(a: (CallbackId, Box<dyn $($typ)+>)) -> Self {
		        $id(a.0, a.1)
		    }
		}
	}
}

callback!(Resize, FnMut(&mut dyn controls::Member, u16, u16));
callback!(Click, FnMut(&mut dyn controls::Clickable));
callback!(Frame, FnMut(&mut dyn controls::Window) -> bool);
<|endoftext|>


<commit_before>use std::iter::FromIterator;

use crate::{
    search_xml::Entry,
    utils::set_or_check,
};
use serde::{
    Deserialize,
    Serialize,
};

use super::gene_member::GeneMember;

#[derive(Debug, Deserialize, Serialize)]
pub struct Gene {
    id: usize,
    name: String,
    assembly_id: String,
    member_count: usize,
    members: Vec<GeneMember>,
}

impl<'a> Gene {
    pub fn as_search(&'a self) -> Entry<'a> {
        let mut entry = Entry::new(&self.name, "", "");

        for member in &self.members {
            entry.add_field("entry_type", "Gene");
            entry.add_field("gene_member", member.urs_taxid());
            entry.add_field("member_description", member.description());

            entry.add_ref("rnacentral", member.urs_taxid());
            for xref in member.cross_references() {
                entry.add_ref(xref.name(), xref.external_id())
            }
        }

        entry
    }
}

impl FromIterator<GeneMember> for Gene {
    fn from_iter<T: IntoIterator<Item = GeneMember>>(iter: T) -> Self {
        let mut locus_id = None;
        let mut name = None;
        let mut member_count = None;
        let mut assembly_id = None;
        let mut members = Vec::new();

        for locus in iter {
            set_or_check(&mut locus_id, locus.locus_id());
            set_or_check(&mut name, locus.name().to_string());
            set_or_check(&mut member_count, *locus.member_count());
            set_or_check(&mut assembly_id, locus.assembly_id().to_string());
            members.push(GeneMember::from(locus));
        }

        Self {
            id: locus_id.unwrap(),
            name: name.unwrap().to_string(),
            member_count: member_count.unwrap().to_owned(),
            assembly_id: assembly_id.unwrap().to_string(),
            members,
        }
    }
}
<commit_msg>Better initialize of entries<commit_after>use std::iter::FromIterator;

use crate::{
    search_xml::Entry,
    utils::set_or_check,
};
use serde::{
    Deserialize,
    Serialize,
};

use super::gene_member::GeneMember;

#[derive(Debug, Deserialize, Serialize)]
pub struct Gene {
    id: usize,
    name: String,
    assembly_id: String,
    member_count: usize,
    members: Vec<GeneMember>,
}

impl<'a> Gene {
    pub fn as_search(&'a self) -> Entry<'a> {
        let mut entry = Entry::new(&self.name, &self.name, "");

        for member in &self.members {
            entry.add_field("entry_type", "Gene");
            entry.add_field("gene_member", member.urs_taxid());
            entry.add_field("member_description", member.description());

            entry.add_ref("rnacentral", member.urs_taxid());
            for xref in member.cross_references() {
                entry.add_ref(xref.name(), xref.external_id())
            }
        }

        entry
    }
}

impl FromIterator<GeneMember> for Gene {
    fn from_iter<T: IntoIterator<Item = GeneMember>>(iter: T) -> Self {
        let mut locus_id = None;
        let mut name = None;
        let mut member_count = None;
        let mut assembly_id = None;
        let mut members = Vec::new();

        for locus in iter {
            set_or_check(&mut locus_id, locus.locus_id());
            set_or_check(&mut name, locus.name().to_string());
            set_or_check(&mut member_count, *locus.member_count());
            set_or_check(&mut assembly_id, locus.assembly_id().to_string());
            members.push(GeneMember::from(locus));
        }

        Self {
            id: locus_id.unwrap(),
            name: name.unwrap().to_string(),
            member_count: member_count.unwrap().to_owned(),
            assembly_id: assembly_id.unwrap().to_string(),
            members,
        }
    }
}
<|endoftext|>


<commit_before>//! Add, remove, or modify a collation
use std::cmp::Ordering;
use std::os::raw::{c_char, c_int, c_void};
use std::panic::{catch_unwind, UnwindSafe};
use std::ptr;
use std::slice;

use crate::ffi;
use crate::{str_to_cstring, Connection, InnerConnection, Result};

// FIXME copy/paste from function.rs
unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
    drop(Box::from_raw(p as *mut T));
}

impl Connection {
    /// Add or modify a collation.
    pub fn create_collation<C>(&self, collation_name: &str, x_compare: C) -> Result<()>
    where
        C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static,
    {
        self.db
            .borrow_mut()
            .create_collation(collation_name, x_compare)
    }

    /// Collation needed callback
    pub fn collation_needed(
        &self,
        x_coll_needed: fn(&Connection, &str) -> Result<()>,
    ) -> Result<()> {
        self.db.borrow_mut().collation_needed(x_coll_needed)
    }

    /// Remove collation.
    pub fn remove_collation(&self, collation_name: &str) -> Result<()> {
        self.db.borrow_mut().remove_collation(collation_name)
    }
}

impl InnerConnection {
    fn create_collation<C>(&mut self, collation_name: &str, x_compare: C) -> Result<()>
    where
        C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static,
    {
        unsafe extern "C" fn call_boxed_closure<C>(
            arg1: *mut c_void,
            arg2: c_int,
            arg3: *const c_void,
            arg4: c_int,
            arg5: *const c_void,
        ) -> c_int
        where
            C: Fn(&str, &str) -> Ordering,
        {
            use std::str;

            let r = catch_unwind(|| {
                let boxed_f: *mut C = arg1 as *mut C;
                assert!(!boxed_f.is_null(), "Internal error - null function pointer");
                let s1 = {
                    let c_slice = slice::from_raw_parts(arg3 as *const u8, arg2 as usize);
                    str::from_utf8_unchecked(c_slice)
                };
                let s2 = {
                    let c_slice = slice::from_raw_parts(arg5 as *const u8, arg4 as usize);
                    str::from_utf8_unchecked(c_slice)
                };
                (*boxed_f)(s1, s2)
            });
            let t = match r {
                Err(_) => {
                    return -1; // FIXME How ?
                }
                Ok(r) => r,
            };

            match t {
                Ordering::Less => -1,
                Ordering::Equal => 0,
                Ordering::Greater => 1,
            }
        }

        let boxed_f: *mut C = Box::into_raw(Box::new(x_compare));
        let c_name = str_to_cstring(collation_name)?;
        let flags = ffi::SQLITE_UTF8;
        let r = unsafe {
            ffi::sqlite3_create_collation_v2(
                self.db(),
                c_name.as_ptr(),
                flags,
                boxed_f as *mut c_void,
                Some(call_boxed_closure::<C>),
                Some(free_boxed_value::<C>),
            )
        };
        self.decode_result(r)
    }

    fn collation_needed(
        &mut self,
        x_coll_needed: fn(&Connection, &str) -> Result<()>,
    ) -> Result<()> {
        use std::mem;
        unsafe extern "C" fn collation_needed_callback(
            arg1: *mut c_void,
            arg2: *mut ffi::sqlite3,
            e_text_rep: c_int,
            arg3: *const c_char,
        ) {
            use std::ffi::CStr;
            use std::str;

            if e_text_rep != ffi::SQLITE_UTF8 {
                // TODO: validate
                return;
            }

            let callback: fn(&Connection, &str) -> Result<()> = mem::transmute(arg1);
            if let Err(_) = catch_unwind(|| {
                let conn = Connection::from_handle(arg2).unwrap();
                let collation_name = {
                    let c_slice = CStr::from_ptr(arg3).to_bytes();
                    str::from_utf8_unchecked(c_slice)
                };
                callback(&conn, collation_name)
            }) {
                return; // FIXME How ?
            }
        }

        let r = unsafe {
            ffi::sqlite3_collation_needed(
                self.db(),
                mem::transmute(x_coll_needed),
                Some(collation_needed_callback),
            )
        };
        self.decode_result(r)
    }

    fn remove_collation(&mut self, collation_name: &str) -> Result<()> {
        let c_name = str_to_cstring(collation_name)?;
        let r = unsafe {
            ffi::sqlite3_create_collation_v2(
                self.db(),
                c_name.as_ptr(),
                ffi::SQLITE_UTF8,
                ptr::null_mut(),
                None,
                None,
            )
        };
        self.decode_result(r)
    }
}

#[cfg(test)]
mod test {
    use crate::{Connection, Result, NO_PARAMS};
    use fallible_streaming_iterator::FallibleStreamingIterator;
    use std::cmp::Ordering;
    use unicase::UniCase;

    fn unicase_compare(s1: &str, s2: &str) -> Ordering {
        UniCase::new(s1).cmp(&UniCase::new(s2))
    }

    #[test]
    fn test_unicase() {
        let db = Connection::open_in_memory().unwrap();

        db.create_collation("unicase", unicase_compare).unwrap();

        collate(db);
    }

    fn collate(db: Connection) {
        db.execute_batch(
            "CREATE TABLE foo (bar);
             INSERT INTO foo (bar) VALUES ('Maße');
             INSERT INTO foo (bar) VALUES ('MASSE');",
        )
        .unwrap();
        let mut stmt = db
            .prepare("SELECT DISTINCT bar COLLATE unicase FROM foo ORDER BY 1")
            .unwrap();
        let rows = stmt.query(NO_PARAMS).unwrap();
        assert_eq!(rows.count().unwrap(), 1);
    }

    fn collation_needed(db: &Connection, collation_name: &str) -> Result<()> {
        if "unicase" == collation_name {
            db.create_collation(collation_name, unicase_compare)
        } else {
            Ok(())
        }
    }

    #[test]
    fn test_collation_needed() {
        let db = Connection::open_in_memory().unwrap();
        db.collation_needed(collation_needed).unwrap();
        collate(db);
    }
}
<commit_msg>Fix Clippy warning<commit_after>//! Add, remove, or modify a collation
use std::cmp::Ordering;
use std::os::raw::{c_char, c_int, c_void};
use std::panic::{catch_unwind, UnwindSafe};
use std::ptr;
use std::slice;

use crate::ffi;
use crate::{str_to_cstring, Connection, InnerConnection, Result};

// FIXME copy/paste from function.rs
unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
    drop(Box::from_raw(p as *mut T));
}

impl Connection {
    /// Add or modify a collation.
    pub fn create_collation<C>(&self, collation_name: &str, x_compare: C) -> Result<()>
    where
        C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static,
    {
        self.db
            .borrow_mut()
            .create_collation(collation_name, x_compare)
    }

    /// Collation needed callback
    pub fn collation_needed(
        &self,
        x_coll_needed: fn(&Connection, &str) -> Result<()>,
    ) -> Result<()> {
        self.db.borrow_mut().collation_needed(x_coll_needed)
    }

    /// Remove collation.
    pub fn remove_collation(&self, collation_name: &str) -> Result<()> {
        self.db.borrow_mut().remove_collation(collation_name)
    }
}

impl InnerConnection {
    fn create_collation<C>(&mut self, collation_name: &str, x_compare: C) -> Result<()>
    where
        C: Fn(&str, &str) -> Ordering + Send + UnwindSafe + 'static,
    {
        unsafe extern "C" fn call_boxed_closure<C>(
            arg1: *mut c_void,
            arg2: c_int,
            arg3: *const c_void,
            arg4: c_int,
            arg5: *const c_void,
        ) -> c_int
        where
            C: Fn(&str, &str) -> Ordering,
        {
            use std::str;

            let r = catch_unwind(|| {
                let boxed_f: *mut C = arg1 as *mut C;
                assert!(!boxed_f.is_null(), "Internal error - null function pointer");
                let s1 = {
                    let c_slice = slice::from_raw_parts(arg3 as *const u8, arg2 as usize);
                    str::from_utf8_unchecked(c_slice)
                };
                let s2 = {
                    let c_slice = slice::from_raw_parts(arg5 as *const u8, arg4 as usize);
                    str::from_utf8_unchecked(c_slice)
                };
                (*boxed_f)(s1, s2)
            });
            let t = match r {
                Err(_) => {
                    return -1; // FIXME How ?
                }
                Ok(r) => r,
            };

            match t {
                Ordering::Less => -1,
                Ordering::Equal => 0,
                Ordering::Greater => 1,
            }
        }

        let boxed_f: *mut C = Box::into_raw(Box::new(x_compare));
        let c_name = str_to_cstring(collation_name)?;
        let flags = ffi::SQLITE_UTF8;
        let r = unsafe {
            ffi::sqlite3_create_collation_v2(
                self.db(),
                c_name.as_ptr(),
                flags,
                boxed_f as *mut c_void,
                Some(call_boxed_closure::<C>),
                Some(free_boxed_value::<C>),
            )
        };
        self.decode_result(r)
    }

    fn collation_needed(
        &mut self,
        x_coll_needed: fn(&Connection, &str) -> Result<()>,
    ) -> Result<()> {
        use std::mem;
        unsafe extern "C" fn collation_needed_callback(
            arg1: *mut c_void,
            arg2: *mut ffi::sqlite3,
            e_text_rep: c_int,
            arg3: *const c_char,
        ) {
            use std::ffi::CStr;
            use std::str;

            if e_text_rep != ffi::SQLITE_UTF8 {
                // TODO: validate
                return;
            }

            let callback: fn(&Connection, &str) -> Result<()> = mem::transmute(arg1);
            if catch_unwind(|| {
                let conn = Connection::from_handle(arg2).unwrap();
                let collation_name = {
                    let c_slice = CStr::from_ptr(arg3).to_bytes();
                    str::from_utf8_unchecked(c_slice)
                };
                callback(&conn, collation_name)
            }).is_err() {
                return; // FIXME How ?
            }
        }

        let r = unsafe {
            ffi::sqlite3_collation_needed(
                self.db(),
                mem::transmute(x_coll_needed),
                Some(collation_needed_callback),
            )
        };
        self.decode_result(r)
    }

    fn remove_collation(&mut self, collation_name: &str) -> Result<()> {
        let c_name = str_to_cstring(collation_name)?;
        let r = unsafe {
            ffi::sqlite3_create_collation_v2(
                self.db(),
                c_name.as_ptr(),
                ffi::SQLITE_UTF8,
                ptr::null_mut(),
                None,
                None,
            )
        };
        self.decode_result(r)
    }
}

#[cfg(test)]
mod test {
    use crate::{Connection, Result, NO_PARAMS};
    use fallible_streaming_iterator::FallibleStreamingIterator;
    use std::cmp::Ordering;
    use unicase::UniCase;

    fn unicase_compare(s1: &str, s2: &str) -> Ordering {
        UniCase::new(s1).cmp(&UniCase::new(s2))
    }

    #[test]
    fn test_unicase() {
        let db = Connection::open_in_memory().unwrap();

        db.create_collation("unicase", unicase_compare).unwrap();

        collate(db);
    }

    fn collate(db: Connection) {
        db.execute_batch(
            "CREATE TABLE foo (bar);
             INSERT INTO foo (bar) VALUES ('Maße');
             INSERT INTO foo (bar) VALUES ('MASSE');",
        )
        .unwrap();
        let mut stmt = db
            .prepare("SELECT DISTINCT bar COLLATE unicase FROM foo ORDER BY 1")
            .unwrap();
        let rows = stmt.query(NO_PARAMS).unwrap();
        assert_eq!(rows.count().unwrap(), 1);
    }

    fn collation_needed(db: &Connection, collation_name: &str) -> Result<()> {
        if "unicase" == collation_name {
            db.create_collation(collation_name, unicase_compare)
        } else {
            Ok(())
        }
    }

    #[test]
    fn test_collation_needed() {
        let db = Connection::open_in_memory().unwrap();
        db.collation_needed(collation_needed).unwrap();
        collate(db);
    }
}
<|endoftext|>


<commit_before>//! Runtime components related to process startup.

use crate::TockSyscalls;
use libtock_platform::RawSyscalls;

/// `set_main!` is used to tell `libtock_runtime` where the process binary's
/// `main` function is. The process binary's `main` function must have the
/// signature `FnOnce() -> T`, where T is some concrete type that implements
/// `libtock_platform::Termination`.
///
/// # Example
/// ```
/// libtock_runtime::set_main!{main};
///
/// fn main() -> () { /* Omitted */ }
/// ```
// set_main! generates a function called `libtock_unsafe_main`, which is called
// by `rust_start`. The function has `unsafe` in its name because implementing
// it is `unsafe` (it *must* have the signature `libtock_unsafe_main() -> !`),
// but there is no way to enforce the use of `unsafe` through the type system.
// This function calls the client-provided function, which enforces its type
// signature.
#[macro_export]
macro_rules! set_main {
    {$name:ident} => {
        #[no_mangle]
        fn libtock_unsafe_main() -> ! {
            use libtock_runtime::TockSyscalls;
            let res = $name();
            #[allow(unreachable_code)] // so that fn main() -> ! does not produce a warning.
            libtock_platform::Termination::complete::<TockSyscalls>(res)
        }
    }
}

/// Executables must specify their stack size by using the `stack_size!` macro.
/// It takes a single argument, the desired stack size in bytes. Example:
/// ```
/// stack_size!{0x400}
/// ```
// stack_size works by putting a symbol equal to the size of the stack in the
// .stack_buffer section. The linker script uses the .stack_buffer section to
// size the stack. flash.sh looks for the symbol by name (hence #[no_mangle]) to
// determine the size of the stack to pass to elf2tab.
#[macro_export]
macro_rules! stack_size {
    {$size:expr} => {
        #[no_mangle]
        #[link_section = ".stack_buffer"]
        pub static mut STACK_MEMORY: [u8; $size] = [0; $size];
    }
}

// rust_start is the first Rust code to execute in the process. It is called
// from start, which is written directly in assembly.
#[no_mangle]
extern "C" fn rust_start() -> ! {
    // TODO: Call memop() to inform the kernel of the stack and size +
    // locations (for debugging).
    // Also, perhaps we should support calling a heap initialization
    // function?

    extern "Rust" {
        // This function is created by the set_main!() macro.
        fn libtock_unsafe_main() -> !;
    }
    // TODO: Provide mechanism for dynamic heap size
    let app_heap_size: usize = 1024;
    unsafe {
        // TODO: Replace with non-raw syscalls once memop
        // implemented.

        // Tell the kernel the new app heap break.
        TockSyscalls::syscall2::<5>([1u32.into(), app_heap_size.into()]);

        libtock_unsafe_main();
    }
}
<commit_msg>Leave startup.rs as-is<commit_after>//! Runtime components related to process startup.

/// `set_main!` is used to tell `libtock_runtime` where the process binary's
/// `main` function is. The process binary's `main` function must have the
/// signature `FnOnce() -> T`, where T is some concrete type that implements
/// `libtock_platform::Termination`.
///
/// # Example
/// ```
/// libtock_runtime::set_main!{main};
///
/// fn main() -> () { /* Omitted */ }
/// ```
// set_main! generates a function called `libtock_unsafe_main`, which is called
// by `rust_start`. The function has `unsafe` in its name because implementing
// it is `unsafe` (it *must* have the signature `libtock_unsafe_main() -> !`),
// but there is no way to enforce the use of `unsafe` through the type system.
// This function calls the client-provided function, which enforces its type
// signature.
#[macro_export]
macro_rules! set_main {
    {$name:ident} => {
        #[no_mangle]
        fn libtock_unsafe_main() -> ! {
            use libtock_runtime::TockSyscalls;
            let res = $name();
            #[allow(unreachable_code)] // so that fn main() -> ! does not produce a warning.
            libtock_platform::Termination::complete::<TockSyscalls>(res)
        }
    }
}

/// Executables must specify their stack size by using the `stack_size!` macro.
/// It takes a single argument, the desired stack size in bytes. Example:
/// ```
/// stack_size!{0x400}
/// ```
// stack_size works by putting a symbol equal to the size of the stack in the
// .stack_buffer section. The linker script uses the .stack_buffer section to
// size the stack. flash.sh looks for the symbol by name (hence #[no_mangle]) to
// determine the size of the stack to pass to elf2tab.
#[macro_export]
macro_rules! stack_size {
    {$size:expr} => {
        #[no_mangle]
        #[link_section = ".stack_buffer"]
        pub static mut STACK_MEMORY: [u8; $size] = [0; $size];
    }
}

// rust_start is the first Rust code to execute in the process. It is called
// from start, which is written directly in assembly.
#[no_mangle]
extern "C" fn rust_start() -> ! {
    // TODO: Call memop() to inform the kernel of the stack and heap sizes +
    // locations. Also, perhaps we should support calling a heap initialization
    // function?

    extern "Rust" {
        fn libtock_unsafe_main() -> !;
    }
    unsafe {
        libtock_unsafe_main();
    }
}
<|endoftext|>


<commit_before>extern crate libc;

use std::ffi::{CString};

#[link(name = "ncurses")]
extern "C" {
    fn getpid() -> i32;
    fn initscr() -> *mut i8;
    fn noecho() -> i32;
    fn curs_set(c: i8) -> i32;
    fn halfdelay(tenths: i8) -> i32;
    #[link_name = "box"]
    fn box_(window: *mut i8, verch: i8, horch: i8);
    fn mvprintw(y: i8, x: i8, s: *const libc::c_char);
    fn getch() -> i8;
    fn endwin() -> libc::c_int;

    fn newwin(nlines: i8, ncols: i8, begin_y: i8, begin_x: i8) -> *mut i8;
    fn wclear(window: *mut i8) -> i8;
    fn wrefresh(window: *mut i8) -> i8;
    fn mvwprintw(window: *mut i8, y: i8, x: i8, s: *const libc::c_char);
    fn wgetch(window: *mut i8) -> i8;
    fn delwin(window: *mut i8) -> i8;
}

trait ToCStr {
    fn to_c_str(&self) -> CString;
}

fn main() {
    unsafe {
        initscr();
        noecho();
        curs_set(0);
        halfdelay(3);

        let width = 20;
        let height = 10;
        let window = newwin(height + 2, width + 2, 0, 0);

        let mut snake = Snake {
            cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
            direction: Direction::Right,
        };

        let mut c = 0;
        while char::from(c as u8) != 'q' {
            wclear(window);
            box_(window, 0, 0);
            mvwprintw(window, snake.head().y + 1, snake.head().x + 1, "Q".to_c_str().as_ptr());
            snake.tail().iter().for_each(|cell|
                mvwprintw(window, cell.y + 1, cell.x + 1, "o".to_c_str().as_ptr())
            );

            wrefresh(window);

            c = wgetch(window);
            let direction = match char::from(c as u8) {
                'i' => Some(Direction::Up),
                'j' => Some(Direction::Left),
                'k' => Some(Direction::Down),
                'l' => Some(Direction::Right),
                _ => Option::None
            };

            if direction.is_some() {
                snake = snake.turn_in(direction.unwrap())
            }
            snake = snake.slide();
        }

        delwin(window);
        endwin();
    }
}

impl<'a> ToCStr for &'a str {
    fn to_c_str(&self) -> CString {
        CString::new(*self).unwrap()
    }
}

#[derive(Debug, PartialEq, Clone)]
struct Snake {
    cells: Vec<Cell>,
    direction: Direction,
}

impl Snake {
    fn head(&self) -> &Cell {
        &self.cells[0]
    }

    fn tail(&self) -> Vec<Cell> {
        self.cells[1..self.cells.len()].to_owned()
    }

    fn turn_in(&self, new_direction: Direction) -> Snake {
        if are_opposite(new_direction, self.direction) {
            self.clone()
        } else {
            Snake { cells: self.cells.clone(), direction: new_direction }
        }
    }

    fn slide(&self) -> Snake {
        let mut vec: Vec<Cell> = vec![self.cells.first().unwrap().move_in(&self.direction)];

        let mut new_cells = self.cells.clone();
        new_cells.pop();
        vec.append(&mut new_cells);

        Snake { cells: vec, direction: self.direction }
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
struct Cell {
    x: i8,
    y: i8,
}

impl Cell {
    fn move_in(&self, direction: &Direction) -> Cell {
        let dx = match direction {
            Direction::Up => 0,
            Direction::Down => 0,
            Direction::Left => -1,
            Direction::Right => 1,
        };
        let dy = match direction {
            Direction::Up => -1,
            Direction::Down => 1,
            Direction::Left => 0,
            Direction::Right => 0,
        };
        return Cell { x: self.x + dx, y: self.y + dy };
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

fn are_opposite(d1: Direction, d2: Direction) -> bool {
    if d1 == Direction::Up && d2 == Direction::Down { return true }
    if d2 == Direction::Up && d1 == Direction::Down { return true }
    if d1 == Direction::Left && d2 == Direction::Right { return true }
    if d2 == Direction::Left && d1 == Direction::Right { return true }
    false
}

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

    #[test]
    fn snake_moves_right() {
        let snake = Snake {
            cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
            direction: Direction::Right,
        };

        assert_eq!(
            snake.slide(),
            Snake {
                cells: vec![Cell { x: 3, y: 0 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Right,
            }
        )
    }

    #[test]
    fn snake_can_change_direction() {
        let snake = Snake {
            cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
            direction: Direction::Right,
        };

        assert_eq!(
            snake.turn_in(Direction::Down).slide(),
            Snake {
                cells: vec![Cell { x: 2, y: 1 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Down,
            }
        );
        assert_eq!(
            snake.turn_in(Direction::Left).slide(),
            Snake {
                cells: vec![Cell { x: 3, y: 0 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Right,
            }
        );
    }
}<commit_msg>extracted Game<commit_after>extern crate libc;

use std::ffi::{CString};

#[link(name = "ncurses")]
#[allow(dead_code)]
extern "C" {
    fn getpid() -> i32;
    fn initscr() -> *mut i8;
    fn noecho() -> i32;
    fn curs_set(c: i8) -> i32;
    fn halfdelay(tenths: i8) -> i32;
    #[link_name = "box"]
    fn box_(window: *mut i8, verch: i8, horch: i8);
    fn mvprintw(y: i8, x: i8, s: *const libc::c_char);
    fn getch() -> i8;
    fn endwin() -> libc::c_int;

    fn newwin(nlines: i8, ncols: i8, begin_y: i8, begin_x: i8) -> *mut i8;
    fn wclear(window: *mut i8) -> i8;
    fn wrefresh(window: *mut i8) -> i8;
    fn mvwprintw(window: *mut i8, y: i8, x: i8, s: *const libc::c_char);
    fn wgetch(window: *mut i8) -> i8;
    fn delwin(window: *mut i8) -> i8;
}

fn main() {
    unsafe {
        initscr();
        noecho();
        curs_set(0);
        halfdelay(3);

        let mut game = Game {
            width: 20,
            height: 10,
            snake: Snake {
                cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
                direction: Direction::Right,
            }
        };
        let window = newwin(game.height + 2, game.width + 2, 0, 0);

        let mut c = 0;
        while char::from(c as u8) != 'q' {
            wclear(window);
            box_(window, 0, 0);

            mvwprintw(window, game.snake.head().y + 1, game.snake.head().x + 1, "Q".to_c_str().as_ptr());
            game.snake.tail().iter().for_each(|cell|
                mvwprintw(window, cell.y + 1, cell.x + 1, "o".to_c_str().as_ptr())
            );

            wrefresh(window);

            c = wgetch(window);
            let direction = match char::from(c as u8) {
                'i' => Some(Direction::Up),
                'j' => Some(Direction::Left),
                'k' => Some(Direction::Down),
                'l' => Some(Direction::Right),
                _ => Option::None
            };

            game = game.update(direction);
        }

        delwin(window);
        endwin();
    }
}

#[derive(Debug, PartialEq, Clone)]
struct Game {
    width: i8,
    height: i8,
    snake: Snake,
}

impl Game {
    fn update(&self, direction: Option<Direction>) -> Game {
        let new_snake;
        if direction.is_some() {
            new_snake = self.snake.turn_in(direction.unwrap()).slide();
        } else {
            new_snake = self.snake.slide();
        }
        return Game {
            width: self.width,
            height: self.height,
            snake: new_snake,
        };
    }
}

#[derive(Debug, PartialEq, Clone)]
struct Snake {
    cells: Vec<Cell>,
    direction: Direction,
}

impl Snake {
    fn head(&self) -> &Cell {
        &self.cells[0]
    }

    fn tail(&self) -> Vec<Cell> {
        self.cells[1..self.cells.len()].to_owned()
    }

    fn turn_in(&self, new_direction: Direction) -> Snake {
        if are_opposite(new_direction, self.direction) {
            self.clone()
        } else {
            Snake { cells: self.cells.clone(), direction: new_direction }
        }
    }

    fn slide(&self) -> Snake {
        let mut vec: Vec<Cell> = vec![self.cells.first().unwrap().move_in(&self.direction)];

        let mut new_cells = self.cells.clone();
        new_cells.pop();
        vec.append(&mut new_cells);

        Snake { cells: vec, direction: self.direction }
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
struct Cell {
    x: i8,
    y: i8,
}

impl Cell {
    fn move_in(&self, direction: &Direction) -> Cell {
        let dx = match direction {
            Direction::Up => 0,
            Direction::Down => 0,
            Direction::Left => -1,
            Direction::Right => 1,
        };
        let dy = match direction {
            Direction::Up => -1,
            Direction::Down => 1,
            Direction::Left => 0,
            Direction::Right => 0,
        };
        return Cell { x: self.x + dx, y: self.y + dy };
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

fn are_opposite(d1: Direction, d2: Direction) -> bool {
    if d1 == Direction::Up && d2 == Direction::Down { return true; }
    if d2 == Direction::Up && d1 == Direction::Down { return true; }
    if d1 == Direction::Left && d2 == Direction::Right { return true; }
    if d2 == Direction::Left && d1 == Direction::Right { return true; }
    false
}

trait ToCStr {
    fn to_c_str(&self) -> CString;
}

impl<'a> ToCStr for &'a str {
    fn to_c_str(&self) -> CString {
        CString::new(*self).unwrap()
    }
}

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

    #[test]
    fn snake_moves_right() {
        let snake = Snake {
            cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
            direction: Direction::Right,
        };

        assert_eq!(
            snake.slide(),
            Snake {
                cells: vec![Cell { x: 3, y: 0 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Right,
            }
        )
    }

    #[test]
    fn snake_can_change_direction() {
        let snake = Snake {
            cells: vec![Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }, Cell { x: 0, y: 0 }],
            direction: Direction::Right,
        };

        assert_eq!(
            snake.turn_in(Direction::Down).slide(),
            Snake {
                cells: vec![Cell { x: 2, y: 1 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Down,
            }
        );
        assert_eq!(
            snake.turn_in(Direction::Left).slide(),
            Snake {
                cells: vec![Cell { x: 3, y: 0 }, Cell { x: 2, y: 0 }, Cell { x: 1, y: 0 }],
                direction: Direction::Right,
            }
        );
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2021-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.

use {
    pyo3::{buffer::PyBuffer, prelude::*},
    zstd_sys::ZSTD_inBuffer,
};

/// Describes a type that can be resolved to a `zstd_sys::ZSTD_inBuffer`.
pub trait InBufferSource {
    /// Obtain the PyObject this instance is reading from.
    fn source_object(&self) -> &PyObject;

    /// Obtain a `zstd_sys::ZSTD_inBuffer` with input to feed to a compressor.
    fn input_buffer(&mut self, py: Python) -> PyResult<Option<ZSTD_inBuffer>>;

    /// Record that `count` bytes were read from the input buffer.
    fn record_bytes_read(&mut self, count: usize);

    /// Whether source data has been fully consumed.
    fn finished(&self) -> bool;
}

/// A data source where data is obtaine by calling `read()`.
struct ReadSource {
    source: PyObject,
    buffer: Option<PyBuffer<u8>>,
    read_size: usize,
    finished: bool,
    offset: usize,
}

impl InBufferSource for ReadSource {
    fn source_object(&self) -> &PyObject {
        &self.source
    }

    fn input_buffer(&mut self, py: Python) -> PyResult<Option<ZSTD_inBuffer>> {
        if self.finished() {
            Ok(None)
        // If we have a buffer, return remaining data in it.
        } else if let Some(buffer) = &self.buffer {
            Ok(Some(ZSTD_inBuffer {
                src: buffer.buf_ptr(),
                size: buffer.len_bytes(),
                pos: self.offset,
            }))
        // Attempt to read new data.
        } else {
            let data = self.source.call_method1(py, "read", (self.read_size,))?;
            let buffer = PyBuffer::get(data.as_ref(py))?;

            if buffer.len_bytes() == 0 {
                self.finished = true;
                Ok(None)
            } else {
                self.buffer = Some(buffer);
                self.offset = 0;

                Ok(Some(ZSTD_inBuffer {
                    src: self.buffer.as_ref().unwrap().buf_ptr(),
                    size: self.buffer.as_ref().unwrap().len_bytes(),
                    pos: self.offset,
                }))
            }
        }
    }

    fn record_bytes_read(&mut self, count: usize) {
        let buffer = self.buffer.as_ref().expect("buffer should be present");

        self.offset += count;

        // If we've exhausted the input buffer, drop it. On next call
        // to input_buffer() we'll try to read() more data and finish
        // the stream if nothing can be read.
        if self.offset >= buffer.len_bytes() {
            self.buffer = None;
        }
    }

    fn finished(&self) -> bool {
        self.finished
    }
}

/// A data source where data is obtained from a `PyObject`
/// conforming to the buffer protocol.
struct BufferSource {
    source: PyObject,
    buffer: PyBuffer<u8>,
    offset: usize,
}

impl InBufferSource for BufferSource {
    fn source_object(&self) -> &PyObject {
        &self.source
    }

    fn input_buffer(&mut self, _py: Python) -> PyResult<Option<ZSTD_inBuffer>> {
        if self.finished() {
            Ok(None)
        } else {
            Ok(Some(ZSTD_inBuffer {
                src: self.buffer.buf_ptr(),
                size: self.buffer.len_bytes(),
                pos: self.offset,
            }))
        }
    }

    fn record_bytes_read(&mut self, count: usize) {
        self.offset += count;
    }

    fn finished(&self) -> bool {
        self.offset >= self.buffer.len_bytes()
    }
}

pub(crate) fn make_in_buffer_source(
    py: Python,
    source: &PyAny,
    read_size: usize,
) -> PyResult<Box<dyn InBufferSource + Send>> {
    if source.hasattr("read")? {
        Ok(Box::new(ReadSource {
            source: source.into_py(py),
            buffer: None,
            read_size,
            finished: false,
            offset: 0,
        }))
    } else {
        let buffer = PyBuffer::get(source)?;

        Ok(Box::new(BufferSource {
            source: source.into_py(py),
            buffer,
            offset: 0,
        }))
    }
}
<commit_msg>rust: cast PyBuffer conversion error to ValueError<commit_after>// Copyright (c) 2021-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.

use {
    pyo3::{buffer::PyBuffer, exceptions::PyValueError, prelude::*},
    zstd_sys::ZSTD_inBuffer,
};

/// Describes a type that can be resolved to a `zstd_sys::ZSTD_inBuffer`.
pub trait InBufferSource {
    /// Obtain the PyObject this instance is reading from.
    fn source_object(&self) -> &PyObject;

    /// Obtain a `zstd_sys::ZSTD_inBuffer` with input to feed to a compressor.
    fn input_buffer(&mut self, py: Python) -> PyResult<Option<ZSTD_inBuffer>>;

    /// Record that `count` bytes were read from the input buffer.
    fn record_bytes_read(&mut self, count: usize);

    /// Whether source data has been fully consumed.
    fn finished(&self) -> bool;
}

/// A data source where data is obtaine by calling `read()`.
struct ReadSource {
    source: PyObject,
    buffer: Option<PyBuffer<u8>>,
    read_size: usize,
    finished: bool,
    offset: usize,
}

impl InBufferSource for ReadSource {
    fn source_object(&self) -> &PyObject {
        &self.source
    }

    fn input_buffer(&mut self, py: Python) -> PyResult<Option<ZSTD_inBuffer>> {
        if self.finished() {
            Ok(None)
        // If we have a buffer, return remaining data in it.
        } else if let Some(buffer) = &self.buffer {
            Ok(Some(ZSTD_inBuffer {
                src: buffer.buf_ptr(),
                size: buffer.len_bytes(),
                pos: self.offset,
            }))
        // Attempt to read new data.
        } else {
            let data = self.source.call_method1(py, "read", (self.read_size,))?;
            let buffer = PyBuffer::get(data.as_ref(py))?;

            if buffer.len_bytes() == 0 {
                self.finished = true;
                Ok(None)
            } else {
                self.buffer = Some(buffer);
                self.offset = 0;

                Ok(Some(ZSTD_inBuffer {
                    src: self.buffer.as_ref().unwrap().buf_ptr(),
                    size: self.buffer.as_ref().unwrap().len_bytes(),
                    pos: self.offset,
                }))
            }
        }
    }

    fn record_bytes_read(&mut self, count: usize) {
        let buffer = self.buffer.as_ref().expect("buffer should be present");

        self.offset += count;

        // If we've exhausted the input buffer, drop it. On next call
        // to input_buffer() we'll try to read() more data and finish
        // the stream if nothing can be read.
        if self.offset >= buffer.len_bytes() {
            self.buffer = None;
        }
    }

    fn finished(&self) -> bool {
        self.finished
    }
}

/// A data source where data is obtained from a `PyObject`
/// conforming to the buffer protocol.
struct BufferSource {
    source: PyObject,
    buffer: PyBuffer<u8>,
    offset: usize,
}

impl InBufferSource for BufferSource {
    fn source_object(&self) -> &PyObject {
        &self.source
    }

    fn input_buffer(&mut self, _py: Python) -> PyResult<Option<ZSTD_inBuffer>> {
        if self.finished() {
            Ok(None)
        } else {
            Ok(Some(ZSTD_inBuffer {
                src: self.buffer.buf_ptr(),
                size: self.buffer.len_bytes(),
                pos: self.offset,
            }))
        }
    }

    fn record_bytes_read(&mut self, count: usize) {
        self.offset += count;
    }

    fn finished(&self) -> bool {
        self.offset >= self.buffer.len_bytes()
    }
}

pub(crate) fn make_in_buffer_source(
    py: Python,
    source: &PyAny,
    read_size: usize,
) -> PyResult<Box<dyn InBufferSource + Send>> {
    if source.hasattr("read")? {
        Ok(Box::new(ReadSource {
            source: source.into_py(py),
            buffer: None,
            read_size,
            finished: false,
            offset: 0,
        }))
    } else {
        let buffer = PyBuffer::get(source).map_err(|_| {
            PyValueError::new_err(
                "must pass an object with a read() method or conforms to buffer protocol",
            )
        })?;

        Ok(Box::new(BufferSource {
            source: source.into_py(py),
            buffer,
            offset: 0,
        }))
    }
}
<|endoftext|>


<commit_before>#[derive(Deserialize, Debug)]
pub struct InitiateMultipartUploadResponse {
    #[serde(rename = "Bucket")]
    _bucket: String,
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "UploadId")]
    pub upload_id: String,
}

/// Owner information for the object
#[derive(Deserialize, Debug, Clone)]
pub struct Owner {
    #[serde(rename = "DisplayName")]
    /// Object owner's name.
    pub display_name: String,
    #[serde(rename = "ID")]
    /// Object owner's ID.
    pub id: String,
}

/// An individual object in a `ListBucketResult`
#[derive(Deserialize, Debug, Clone)]
pub struct Object {
    #[serde(rename = "LastModified")]
    /// Date and time the object was last modified.
    pub last_modified: String,
    #[serde(rename = "ETag")]
    /// The entity tag is an MD5 hash of the object. The ETag only reflects changes to the
    /// contents of an object, not its metadata.
    pub e_tag: String,
    #[serde(rename = "StorageClass")]
    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
    pub storage_class: Option<String>,
    #[serde(rename = "Key")]
    /// The object's key
    pub key: String,
    #[serde(rename = "Owner")]
    /// Bucket owner
    pub owner: Option<Owner>,
    #[serde(rename = "Size")]
    /// Size in bytes of the object.
    pub size: u64,
}

/// An individual upload in a `ListMultipartUploadsResult`
#[derive(Deserialize, Debug, Clone)]
pub struct MultipartUpload {
    #[serde(rename = "Initiated")]
    /// Date and time the multipart upload was initiated
    pub initiated: String,
    #[serde(rename = "StorageClass")]
    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
    pub storage_class: String,
    #[serde(rename = "Key")]
    /// The object's key
    pub key: String,
    #[serde(rename = "Owner")]
    /// Bucket owner
    pub owner: Option<Owner>,
    #[serde(rename = "UploadId")]
    /// The identifier of the upload
    pub id: String,
}

use std::fmt;

impl fmt::Display for CompleteMultipartUploadData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = String::new();
        for part in self.parts.clone() {
            parts.push_str(&serde_xml_rs::to_string(&part).unwrap())
        }
        write!(
            f,
            "<CompleteMultipartUpload>{}</CompleteMultipartUpload>",
            parts
        )
    }
}

impl CompleteMultipartUploadData {
    pub fn len(&self) -> usize {
        self.to_string().as_bytes().len()
    }

    pub fn is_empty(&self) -> bool {
        self.to_string().as_bytes().len() == 0
    }
}

#[derive(Debug, Clone)]
pub struct CompleteMultipartUploadData {
    pub parts: Vec<Part>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Part {
    #[serde(rename = "PartNumber")]
    pub part_number: u32,
    #[serde(rename = "ETag")]
    pub etag: String,
}

#[derive(Deserialize, Debug, Clone)]
pub struct BucketLocationResult {
    #[serde(rename = "$value")]
    pub region: String,
}

/// The parsed result of a s3 bucket listing
///
/// This accepts the ListBucketResult format returned for both ListObjects and ListObjectsV2
#[derive(Deserialize, Debug, Clone)]
pub struct ListBucketResult {
    #[serde(rename = "Name")]
    /// Name of the bucket.
    pub name: String,
    #[serde(rename = "Delimiter")]
    /// A delimiter is a character you use to group keys.
    pub delimiter: Option<String>,
    #[serde(rename = "MaxKeys")]
    /// Sets the maximum number of keys returned in the response body.
    pub max_keys: Option<i32>,
    #[serde(rename = "Prefix")]
    /// Limits the response to keys that begin with the specified prefix.
    pub prefix: String,
    #[serde(rename = "ContinuationToken")] // for ListObjectsV2 request
    #[serde(alias = "Marker")] // for ListObjects request
    /// Indicates where in the bucket listing begins. It is included in the response if
    /// it was sent with the request.
    pub continuation_token: Option<String>,
    #[serde(rename = "EncodingType")]
    /// Specifies the encoding method to used
    pub encoding_type: Option<String>,
    #[serde(
        rename = "IsTruncated",
        deserialize_with = "super::deserializer::bool_deserializer"
    )]
    ///  Specifies whether (true) or not (false) all of the results were returned.
    ///  If the number of results exceeds that specified by MaxKeys, all of the results
    ///  might not be returned.

    /// When the response is truncated (that is, the IsTruncated element value in the response
    /// is true), you can use the key name in in 'next_continuation_token' as a marker in the
    /// subsequent request to get next set of objects. Amazon S3 lists objects in UTF-8 character
    /// encoding in lexicographical order.
    pub is_truncated: bool,
    #[serde(rename = "NextContinuationToken", default)] // for ListObjectsV2 request
    #[serde(alias = "NextMarker")] // for ListObjects request
    pub next_continuation_token: Option<String>,
    #[serde(rename = "Contents", default)]
    /// Metadata about each object returned.
    pub contents: Vec<Object>,
    #[serde(rename = "CommonPrefixes", default)]
    /// All of the keys rolled up into a common prefix count as a single return when
    /// calculating the number of returns.
    pub common_prefixes: Option<Vec<CommonPrefix>>,
}

/// The parsed result of a s3 bucket listing of uploads
#[derive(Deserialize, Debug, Clone)]
pub struct ListMultipartUploadsResult {
    #[serde(rename = "Bucket")]
    /// Name of the bucket.
    pub name: String,
    #[serde(rename = "NextKeyMarker")]
    /// When the response is truncated (that is, the IsTruncated element value in the response
    /// is true), you can use the key name in this field as a marker in the subsequent request
    /// to get next set of objects. Amazon S3 lists objects in UTF-8 character encoding in
    /// lexicographical order.
    pub next_marker: Option<String>,
    #[serde(rename = "Prefix")]
    /// The prefix, present if the request contained a prefix too, shows the search root for the
    /// uploads listed in this structure.
    pub prefix: Option<String>,
    #[serde(rename = "KeyMarker")]
    /// Indicates where in the bucket listing begins.
    pub marker: Option<String>,
    #[serde(rename = "EncodingType")]
    /// Specifies the encoding method to used
    pub encoding_type: Option<String>,
    #[serde(
        rename = "IsTruncated",
        deserialize_with = "super::deserializer::bool_deserializer"
    )]
    ///  Specifies whether (true) or not (false) all of the results were returned.
    ///  If the number of results exceeds that specified by MaxKeys, all of the results
    ///  might not be returned.
    pub is_truncated: bool,
    #[serde(rename = "Upload", default)]
    /// Metadata about each upload returned.
    pub uploads: Vec<MultipartUpload>,
    #[serde(rename = "CommonPrefixes", default)]
    /// All of the keys rolled up into a common prefix count as a single return when
    /// calculating the number of returns.
    pub common_prefixes: Option<Vec<CommonPrefix>>,
}

/// `CommonPrefix` is used to group keys
#[derive(Deserialize, Debug, Clone)]
pub struct CommonPrefix {
    #[serde(rename = "Prefix")]
    /// Keys that begin with the indicated prefix.
    pub prefix: String,
}

// Taken from https://github.com/rusoto/rusoto
#[derive(Deserialize, Debug, Default, Clone)]
pub struct HeadObjectResult {
    #[serde(rename = "AcceptRanges")]
    /// Indicates that a range of bytes was specified.
    pub accept_ranges: Option<String>,
    #[serde(rename = "CacheControl")]
    /// Specifies caching behavior along the request/reply chain.
    pub cache_control: Option<String>,
    #[serde(rename = "ContentDisposition")]
    /// Specifies presentational information for the object.
    pub content_disposition: Option<String>,
    #[serde(rename = "ContentEncoding")]
    /// Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field.
    pub content_encoding: Option<String>,
    #[serde(rename = "ContentLanguage")]
    /// The language the content is in.
    pub content_language: Option<String>,
    #[serde(rename = "ContentLength")]
    /// Size of the body in bytes.
    pub content_length: Option<i64>,
    #[serde(rename = "ContentType")]
    /// A standard MIME type describing the format of the object data.
    pub content_type: Option<String>,
    #[serde(rename = "DeleteMarker")]
    /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker.
    pub delete_marker: Option<bool>,
    #[serde(rename = "ETag")]
    /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL.
    pub e_tag: Option<String>,
    #[serde(rename = "Expiration")]
    /// If the object expiration is configured, the response includes this header. It includes the expiry-date and rule-id key-value pairs providing object expiration information.
    /// The value of the rule-id is URL encoded.
    pub expiration: Option<String>,
    #[serde(rename = "Expires")]
    /// The date and time at which the object is no longer cacheable.
    pub expires: Option<String>,
    #[serde(rename = "LastModified")]
    /// Last modified date of the object
    pub last_modified: Option<String>,
    #[serde(rename = "Metadata", default)]
    /// A map of metadata to store with the object in S3.
    pub metadata: Option<::std::collections::HashMap<String, String>>,
    #[serde(rename = "MissingMeta")]
    /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like SOAP that supports more flexible metadata than
    /// the REST API. For example, using SOAP, you can create metadata whose values are not legal HTTP headers.
    pub missing_meta: Option<i64>,
    #[serde(rename = "ObjectLockLegalHoldStatus")]
    /// Specifies whether a legal hold is in effect for this object. This header is only returned if the requester has the s3:GetObjectLegalHold permission.
    /// This header is not returned if the specified version of this object has never had a legal hold applied.
    pub object_lock_legal_hold_status: Option<String>,
    #[serde(rename = "ObjectLockMode")]
    /// The Object Lock mode, if any, that's in effect for this object.
    pub object_lock_mode: Option<String>,
    #[serde(rename = "ObjectLockRetainUntilDate")]
    /// The date and time when the Object Lock retention period expires.
    /// This header is only returned if the requester has the s3:GetObjectRetention permission.
    pub object_lock_retain_until_date: Option<String>,
    #[serde(rename = "PartsCount")]
    /// The count of parts this object has.
    pub parts_count: Option<i64>,
    #[serde(rename = "ReplicationStatus")]
    /// If your request involves a bucket that is either a source or destination in a replication rule.
    pub replication_status: Option<String>,
    #[serde(rename = "RequestCharged")]
    pub request_charged: Option<String>,
    #[serde(rename = "Restore")]
    /// If the object is an archived object (an object whose storage class is GLACIER), the response includes this header if either the archive restoration is in progress or an archive copy is already restored.
    /// If an archive copy is already restored, the header value indicates when Amazon S3 is scheduled to delete the object copy.
    pub restore: Option<String>,
    #[serde(rename = "SseCustomerAlgorithm")]
    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header confirming the encryption algorithm used.
    pub sse_customer_algorithm: Option<String>,
    #[serde(rename = "SseCustomerKeyMd5")]
    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header to provide round-trip message integrity verification of the customer-provided encryption key.
    pub sse_customer_key_md5: Option<String>,
    #[serde(rename = "SsekmsKeyId")]
    /// If present, specifies the ID of the AWS Key Management Service (AWS KMS) symmetric customer managed customer master key (CMK) that was used for the object.
    pub ssekms_key_id: Option<String>,
    #[serde(rename = "ServerSideEncryption")]
    /// If the object is stored using server-side encryption either with an AWS KMS customer master key (CMK) or an Amazon S3-managed encryption key,
    /// The response includes this header with the value of the server-side encryption algorithm used when storing this object in Amazon S3 (for example, AES256, aws:kms).
    pub server_side_encryption: Option<String>,
    #[serde(rename = "StorageClass")]
    /// Provides storage class information of the object. Amazon S3 returns this header for all objects except for S3 Standard storage class objects.
    pub storage_class: Option<String>,
    #[serde(rename = "VersionId")]
    /// Version of the object.
    pub version_id: Option<String>,
    #[serde(rename = "WebsiteRedirectLocation")]
    /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata.
    pub website_redirect_location: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct AwsError {
    #[serde(rename = "Code")]
    pub code: String,
    #[serde(rename = "Message")]
    pub message: String,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}
<commit_msg>make some fields in struct ListBucketResult optional (#267)<commit_after>#[derive(Deserialize, Debug)]
pub struct InitiateMultipartUploadResponse {
    #[serde(rename = "Bucket")]
    _bucket: String,
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "UploadId")]
    pub upload_id: String,
}

/// Owner information for the object
#[derive(Deserialize, Debug, Clone)]
pub struct Owner {
    #[serde(rename = "DisplayName")]
    /// Object owner's name.
    pub display_name: Option<String>,
    #[serde(rename = "ID")]
    /// Object owner's ID.
    pub id: String,
}

/// An individual object in a `ListBucketResult`
#[derive(Deserialize, Debug, Clone)]
pub struct Object {
    #[serde(rename = "LastModified")]
    /// Date and time the object was last modified.
    pub last_modified: String,
    #[serde(rename = "ETag")]
    /// The entity tag is an MD5 hash of the object. The ETag only reflects changes to the
    /// contents of an object, not its metadata.
    pub e_tag: Option<String>,
    #[serde(rename = "StorageClass")]
    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
    pub storage_class: Option<String>,
    #[serde(rename = "Key")]
    /// The object's key
    pub key: String,
    #[serde(rename = "Owner")]
    /// Bucket owner
    pub owner: Option<Owner>,
    #[serde(rename = "Size")]
    /// Size in bytes of the object.
    pub size: u64,
}

/// An individual upload in a `ListMultipartUploadsResult`
#[derive(Deserialize, Debug, Clone)]
pub struct MultipartUpload {
    #[serde(rename = "Initiated")]
    /// Date and time the multipart upload was initiated
    pub initiated: String,
    #[serde(rename = "StorageClass")]
    /// STANDARD | STANDARD_IA | REDUCED_REDUNDANCY | GLACIER
    pub storage_class: String,
    #[serde(rename = "Key")]
    /// The object's key
    pub key: String,
    #[serde(rename = "Owner")]
    /// Bucket owner
    pub owner: Option<Owner>,
    #[serde(rename = "UploadId")]
    /// The identifier of the upload
    pub id: String,
}

use std::fmt;

impl fmt::Display for CompleteMultipartUploadData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = String::new();
        for part in self.parts.clone() {
            parts.push_str(&serde_xml_rs::to_string(&part).unwrap())
        }
        write!(
            f,
            "<CompleteMultipartUpload>{}</CompleteMultipartUpload>",
            parts
        )
    }
}

impl CompleteMultipartUploadData {
    pub fn len(&self) -> usize {
        self.to_string().as_bytes().len()
    }

    pub fn is_empty(&self) -> bool {
        self.to_string().as_bytes().len() == 0
    }
}

#[derive(Debug, Clone)]
pub struct CompleteMultipartUploadData {
    pub parts: Vec<Part>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Part {
    #[serde(rename = "PartNumber")]
    pub part_number: u32,
    #[serde(rename = "ETag")]
    pub etag: String,
}

#[derive(Deserialize, Debug, Clone)]
pub struct BucketLocationResult {
    #[serde(rename = "$value")]
    pub region: String,
}

/// The parsed result of a s3 bucket listing
///
/// This accepts the ListBucketResult format returned for both ListObjects and ListObjectsV2
#[derive(Deserialize, Debug, Clone)]
pub struct ListBucketResult {
    #[serde(rename = "Name")]
    /// Name of the bucket.
    pub name: String,
    #[serde(rename = "Delimiter")]
    /// A delimiter is a character you use to group keys.
    pub delimiter: Option<String>,
    #[serde(rename = "MaxKeys")]
    /// Sets the maximum number of keys returned in the response body.
    pub max_keys: Option<i32>,
    #[serde(rename = "Prefix")]
    /// Limits the response to keys that begin with the specified prefix.
    pub prefix: Option<String>,
    #[serde(rename = "ContinuationToken")] // for ListObjectsV2 request
    #[serde(alias = "Marker")] // for ListObjects request
    /// Indicates where in the bucket listing begins. It is included in the response if
    /// it was sent with the request.
    pub continuation_token: Option<String>,
    #[serde(rename = "EncodingType")]
    /// Specifies the encoding method to used
    pub encoding_type: Option<String>,
    #[serde(
        default,
        rename = "IsTruncated",
        deserialize_with = "super::deserializer::bool_deserializer"
    )]
    ///  Specifies whether (true) or not (false) all of the results were returned.
    ///  If the number of results exceeds that specified by MaxKeys, all of the results
    ///  might not be returned.

    /// When the response is truncated (that is, the IsTruncated element value in the response
    /// is true), you can use the key name in in 'next_continuation_token' as a marker in the
    /// subsequent request to get next set of objects. Amazon S3 lists objects in UTF-8 character
    /// encoding in lexicographical order.
    pub is_truncated: bool,
    #[serde(rename = "NextContinuationToken", default)] // for ListObjectsV2 request
    #[serde(alias = "NextMarker")] // for ListObjects request
    pub next_continuation_token: Option<String>,
    #[serde(rename = "Contents", default)]
    /// Metadata about each object returned.
    pub contents: Vec<Object>,
    #[serde(rename = "CommonPrefixes", default)]
    /// All of the keys rolled up into a common prefix count as a single return when
    /// calculating the number of returns.
    pub common_prefixes: Option<Vec<CommonPrefix>>,
}

/// The parsed result of a s3 bucket listing of uploads
#[derive(Deserialize, Debug, Clone)]
pub struct ListMultipartUploadsResult {
    #[serde(rename = "Bucket")]
    /// Name of the bucket.
    pub name: String,
    #[serde(rename = "NextKeyMarker")]
    /// When the response is truncated (that is, the IsTruncated element value in the response
    /// is true), you can use the key name in this field as a marker in the subsequent request
    /// to get next set of objects. Amazon S3 lists objects in UTF-8 character encoding in
    /// lexicographical order.
    pub next_marker: Option<String>,
    #[serde(rename = "Prefix")]
    /// The prefix, present if the request contained a prefix too, shows the search root for the
    /// uploads listed in this structure.
    pub prefix: Option<String>,
    #[serde(rename = "KeyMarker")]
    /// Indicates where in the bucket listing begins.
    pub marker: Option<String>,
    #[serde(rename = "EncodingType")]
    /// Specifies the encoding method to used
    pub encoding_type: Option<String>,
    #[serde(
        rename = "IsTruncated",
        deserialize_with = "super::deserializer::bool_deserializer"
    )]
    ///  Specifies whether (true) or not (false) all of the results were returned.
    ///  If the number of results exceeds that specified by MaxKeys, all of the results
    ///  might not be returned.
    pub is_truncated: bool,
    #[serde(rename = "Upload", default)]
    /// Metadata about each upload returned.
    pub uploads: Vec<MultipartUpload>,
    #[serde(rename = "CommonPrefixes", default)]
    /// All of the keys rolled up into a common prefix count as a single return when
    /// calculating the number of returns.
    pub common_prefixes: Option<Vec<CommonPrefix>>,
}

/// `CommonPrefix` is used to group keys
#[derive(Deserialize, Debug, Clone)]
pub struct CommonPrefix {
    #[serde(rename = "Prefix")]
    /// Keys that begin with the indicated prefix.
    pub prefix: String,
}

// Taken from https://github.com/rusoto/rusoto
#[derive(Deserialize, Debug, Default, Clone)]
pub struct HeadObjectResult {
    #[serde(rename = "AcceptRanges")]
    /// Indicates that a range of bytes was specified.
    pub accept_ranges: Option<String>,
    #[serde(rename = "CacheControl")]
    /// Specifies caching behavior along the request/reply chain.
    pub cache_control: Option<String>,
    #[serde(rename = "ContentDisposition")]
    /// Specifies presentational information for the object.
    pub content_disposition: Option<String>,
    #[serde(rename = "ContentEncoding")]
    /// Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field.
    pub content_encoding: Option<String>,
    #[serde(rename = "ContentLanguage")]
    /// The language the content is in.
    pub content_language: Option<String>,
    #[serde(rename = "ContentLength")]
    /// Size of the body in bytes.
    pub content_length: Option<i64>,
    #[serde(rename = "ContentType")]
    /// A standard MIME type describing the format of the object data.
    pub content_type: Option<String>,
    #[serde(rename = "DeleteMarker")]
    /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker.
    pub delete_marker: Option<bool>,
    #[serde(rename = "ETag")]
    /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL.
    pub e_tag: Option<String>,
    #[serde(rename = "Expiration")]
    /// If the object expiration is configured, the response includes this header. It includes the expiry-date and rule-id key-value pairs providing object expiration information.
    /// The value of the rule-id is URL encoded.
    pub expiration: Option<String>,
    #[serde(rename = "Expires")]
    /// The date and time at which the object is no longer cacheable.
    pub expires: Option<String>,
    #[serde(rename = "LastModified")]
    /// Last modified date of the object
    pub last_modified: Option<String>,
    #[serde(rename = "Metadata", default)]
    /// A map of metadata to store with the object in S3.
    pub metadata: Option<::std::collections::HashMap<String, String>>,
    #[serde(rename = "MissingMeta")]
    /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like SOAP that supports more flexible metadata than
    /// the REST API. For example, using SOAP, you can create metadata whose values are not legal HTTP headers.
    pub missing_meta: Option<i64>,
    #[serde(rename = "ObjectLockLegalHoldStatus")]
    /// Specifies whether a legal hold is in effect for this object. This header is only returned if the requester has the s3:GetObjectLegalHold permission.
    /// This header is not returned if the specified version of this object has never had a legal hold applied.
    pub object_lock_legal_hold_status: Option<String>,
    #[serde(rename = "ObjectLockMode")]
    /// The Object Lock mode, if any, that's in effect for this object.
    pub object_lock_mode: Option<String>,
    #[serde(rename = "ObjectLockRetainUntilDate")]
    /// The date and time when the Object Lock retention period expires.
    /// This header is only returned if the requester has the s3:GetObjectRetention permission.
    pub object_lock_retain_until_date: Option<String>,
    #[serde(rename = "PartsCount")]
    /// The count of parts this object has.
    pub parts_count: Option<i64>,
    #[serde(rename = "ReplicationStatus")]
    /// If your request involves a bucket that is either a source or destination in a replication rule.
    pub replication_status: Option<String>,
    #[serde(rename = "RequestCharged")]
    pub request_charged: Option<String>,
    #[serde(rename = "Restore")]
    /// If the object is an archived object (an object whose storage class is GLACIER), the response includes this header if either the archive restoration is in progress or an archive copy is already restored.
    /// If an archive copy is already restored, the header value indicates when Amazon S3 is scheduled to delete the object copy.
    pub restore: Option<String>,
    #[serde(rename = "SseCustomerAlgorithm")]
    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header confirming the encryption algorithm used.
    pub sse_customer_algorithm: Option<String>,
    #[serde(rename = "SseCustomerKeyMd5")]
    /// If server-side encryption with a customer-provided encryption key was requested, the response will include this header to provide round-trip message integrity verification of the customer-provided encryption key.
    pub sse_customer_key_md5: Option<String>,
    #[serde(rename = "SsekmsKeyId")]
    /// If present, specifies the ID of the AWS Key Management Service (AWS KMS) symmetric customer managed customer master key (CMK) that was used for the object.
    pub ssekms_key_id: Option<String>,
    #[serde(rename = "ServerSideEncryption")]
    /// If the object is stored using server-side encryption either with an AWS KMS customer master key (CMK) or an Amazon S3-managed encryption key,
    /// The response includes this header with the value of the server-side encryption algorithm used when storing this object in Amazon S3 (for example, AES256, aws:kms).
    pub server_side_encryption: Option<String>,
    #[serde(rename = "StorageClass")]
    /// Provides storage class information of the object. Amazon S3 returns this header for all objects except for S3 Standard storage class objects.
    pub storage_class: Option<String>,
    #[serde(rename = "VersionId")]
    /// Version of the object.
    pub version_id: Option<String>,
    #[serde(rename = "WebsiteRedirectLocation")]
    /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata.
    pub website_redirect_location: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct AwsError {
    #[serde(rename = "Code")]
    pub code: String,
    #[serde(rename = "Message")]
    pub message: String,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}
<|endoftext|>