<commit_before>//! Cartridge emulation. There are multiple cartridge types with
//! different capabilities (bankable ROM/RAM, battery, RTC etc...).

use std::fmt::{Debug, Formatter, Error};
use std::path::{Path, PathBuf};
use std::fs::{File, OpenOptions};
use std::iter::repeat;
use ascii::AsciiCast;
use std::io::{SeekFrom, Read, Write, Seek};
use std::io::Result as IoResult;

mod models;

/// Common state for all cartridge types
pub struct Cartridge {
    /// Cartridge ROM data
    rom:        Vec<u8>,
    /// Cartridge RAM data
    ram:        Vec<u8>,
    /// Total number of ROM banks in this cart
    rom_banks:  u8,
    /// Current number of the rom bank mapped at [0x4000, 0x7fff]
    rom_bank:   u8,
    /// Current bank offset for the bank mapped at [0x4000, 0x7fff].
    /// This value is added to ROM register addresses when they're in
    /// that range.
    rom_offset: i32,
    /// Current bank offset for the RAM
    ram_offset: u32,
    /// If `true` RAM is write protected
    ram_wp:     bool,
    /// Certain cartridges allow banking either the RAM or ROM
    /// depending on the value of this flag.
    bank_ram:   bool,
    /// struct used to handle model specific functions
    model:      models::Model,
    /// Path to the ROM image for this cartridge
    path:       PathBuf,
    /// optional save file used to store non-volatile RAM on emulator
    /// shutdown
    save_file:  Option<File>,
}

impl Cartridge {
    /// Load a Cartridge ROM from `path`.
    pub fn from_path(rom_path: &Path) -> IoResult<Cartridge> {
        let mut source = try!(File::open(rom_path));

        let mut rom = Vec::new();

        // There must always be at least two ROM banks
        try!((&mut source).take(2 * ROM_BANK_SIZE as u64)
             .read_to_end(&mut rom));

        let model = models::from_id(rom[offsets::TYPE]);

        let mut cartridge = Cartridge {
            rom:        rom,
            ram:        Vec::new(),
            rom_banks:  2,
            // Default to bank 1 for bankable region
            rom_bank:   1,
            rom_offset: 0,
            ram_offset: 0,
            ram_wp:     true,
            bank_ram:   false,
            model:      model,
            path:       PathBuf::from(rom_path),
            save_file:  None,
        };

        let rombanks = match cartridge.parse_rom_banks() {
            Some(n) => n,
            None    => panic!("Can't determine ROM size"),
        };

        cartridge.rom_banks = rombanks;

        // Read the remaining roms banks
        if rombanks > 2 {
            let remb      = (rombanks - 2) as usize;
            let mut off   = 2    * ROM_BANK_SIZE as usize;
            let mut remsz = remb * ROM_BANK_SIZE as usize;

            // Reserve space for the remaining banks
            cartridge.rom.extend(repeat(0).take(remsz));

            while remsz > 0 {
                let r = try!(source.read(&mut cartridge.rom[off..]));

                remsz -= r;
                off   += r;
            }
        }

        try!(cartridge.init_ram());

        Ok(cartridge)
    }

    /// Init cartridge RAM and tie it with a `File` for saving if
    /// necessary.
    fn init_ram(&mut self) -> IoResult<()> {
        let (rambanks, banksize) = match self.parse_ram_banks() {
            Some(v) => v,
            None    => panic!("Can't determine RAM size"),
        };

        let ramsize = rambanks * banksize;

        if ramsize == 0 {
            // No RAM on this cartridge, we're done
            return Ok(());
        }

        // We have some RAM, open the save file or create it if it
        // doesn't exist yet
        let mut savepath = self.path.clone();
        savepath.set_extension("sav");

        let mut save_file = try!(OpenOptions::new().read(true).write(true)
                                 .open(savepath.clone()));

        let save_size = try!(save_file.metadata()).len();

        if save_size == 0 {
            // The file is empty (probably new). initialize
            // the RAM with 0s.
            self.ram = vec![0; ramsize];
            // Then fill the file with the right amount of 0s
            // to reserve enough space for saving later.
            try!(save_file.write_all(&self.ram));
        } else if save_size == (ramsize as u64) {
            // The file contains a RAM image
            try!((&mut save_file).take(ramsize as u64).read_to_end(&mut self.ram));
        } else {
            panic!("Unexpected save file size for {}: expected {} got {}",
                   savepath.display(), ramsize, save_size);
        }

        // Store the file handle to save progress later
        self.save_file = Some(save_file);

        Ok(())
    }

    /// Update the save file
    pub fn save_ram(&mut self) -> IoResult<()> {
        if let Some(mut f) = self.save_file.as_mut() {
            // Rewind to the beginning of the file and update its
            // contents
            println!("Saving non-volatile memory");

            try!(f.seek(SeekFrom::Start(0)));
            try!(f.write_all(&self.ram));
        }

        Ok(())
    }

    /// Attempt to retreive the rom's name
    pub fn name(&self) -> Option<String> {
        let mut name = String::with_capacity(16);

        for i in 0..16 {
            let c =
                match self.rom[offsets::TITLE + i].to_ascii() {
                    Ok(c) => c,
                    _     => return None,
                };

            // If the name is shorter than 16bytes it's padded with 0s
            if c.as_byte() == 0 {
                break;
            }

            // Only uppercase ASCII is valid, but let's be a little
            // more lenient
            if !c.is_print() {
                return None;
            }

            // Append new character
            name.push(c.as_char());
        }

        Some(name)
    }

    /// Return the number of ROM banks declared in the header. Each
    /// bank is 16KB.
    fn parse_rom_banks(&self) -> Option<u8> {
        let id = self.rom_byte(offsets::ROM_SIZE as u16);

        let nbanks =
            match id {
                0x00 => 2,
                0x01 => 4,
                0x02 => 8,
                0x03 => 16,
                0x04 => 32,
                0x05 => 64,
                0x06 => 128,
                0x52 => 72,
                0x53 => 80,
                0x54 => 96,
                // Unknown value
                _    => return None,
            };

        Some(nbanks)
    }

    /// Return the number of RAM banks for this ROM along with the
    /// size of each bank in bytes.
    pub fn parse_ram_banks(&self) -> Option<(usize, usize)> {

        let model = models::from_id(self.rom_byte(offsets::TYPE as u16));

        // Special case for MBC2, the RAM_SIZE field is not
        // trustworthy here (it advertises 0 banks but there's still
        // some RAM on the cartridge).
        if model.name == "MBC2" {
            // MBC2 contains 1 "bank" of 256bytes
            return Some((1, 256));
        }

        let id = self.rom_byte(offsets::RAM_SIZE as u16);

        let (nbanks, bank_size_kb) =
            match id {
                0x00 => (0,  0),
                0x01 => (1,  2),
                0x02 => (1,  8),
                0x03 => (4,  8),
                0x04 => (16, 8),
                // Unknown value
                _    => return None,
            };

        Some((nbanks, bank_size_kb * 1024))
    }

    pub fn rom_byte(&self, offset: u16) -> u8 {
        let off = offset as i32;

        if off < ROM_BANK_SIZE {
            self.rom[off as usize]
        } else {
            self.rom[(self.rom_offset + off) as usize]
        }
    }

    pub fn set_rom_byte(&mut self, offset: u16, val: u8) {
        (self.model.write_rom)(self, offset, val)
    }

    /// Return the value of RAM byte at `offset` in the currently
    /// selected RAM bank
    pub fn ram_byte(&self, offset: u16) -> u8 {
        let addr = self.ram_offset + offset as u32;

        (self.model.read_ram)(self, addr)
    }

    /// Return the value of a RAM byte at absolute address `addr`
    fn ram_byte_absolute(&self, addr: u32) -> u8 {
        *self.ram.get(addr as usize).unwrap_or(&0)
    }

    fn ram_byte_absolute_mut(&mut self, addr: u32) -> Option<&mut u8> {
        self.ram.get_mut(addr as usize)
    }

    /// Set value of RAM byte at `offset` in the curretly selected RAM
    /// bank
    pub fn set_ram_byte(&mut self, offset: u16, val: u8) {
        let addr = self.ram_offset + offset as u32;

        if self.ram_wp {
            debug!("Attempt to write to cartridge RAM while protected");
            return;
        }

        (self.model.write_ram)(self, addr, val);
    }

    /// Retreive the number of ROM banks in the cartridge
    pub fn rom_banks(&self) -> u8 {
        self.rom_banks
    }

    /// Retrieve current ROM bank number for the bankable range at
    /// [0x4000, 0x7fff]
    pub fn rom_bank(&self) -> u8 {
        self.rom_bank
    }

    /// Set new ROM bank number for the bankable range at
    /// [0x4000, 0x7fff]
    pub fn set_rom_bank(&mut self, bank: u8) {
        self.rom_bank = bank;
    }

    pub fn set_rom_offset(&mut self, offset: i32) {
        self.rom_offset = offset;
    }

    /// Enable or disable RAM write protect
    pub fn set_ram_wp(&mut self, wp: bool) {
        self.ram_wp = wp
    }

    /// Return the value of the `bank_ram` flag
    pub fn bank_ram(&self) -> bool {
        self.bank_ram
    }

    /// Set the value of the `bank_ram` flag
    pub fn set_bank_ram(&mut self, v: bool) {
        self.bank_ram = v
    }

    /// Set new RAM bank number
    pub fn set_ram_bank(&mut self, bank: u8) {
        // Bankable RAM is always 8KB per bank
        self.ram_offset = bank as u32 * 8 * 1024;
    }

    /// Create a Cartridge instance from a ROM provided in a
    /// Vec<u8>. Usefull for tests. Creates a MBC0 model without
    /// banking.
    #[cfg(test)]
    pub fn from_vec(rom: Vec<u8>) -> Cartridge {
        Cartridge {
            rom:        rom,
            ram:        Vec::new(),
            rom_bank:   1,
            rom_banks:  2,
            rom_offset: 0,
            ram_offset: 0,
            ram_wp:     true,
            bank_ram:   false,
            model:      models::from_id(0x00),
            path:       PathBuf::from("dummy"),
            save_file:  None,
        }
    }
}

impl Drop for Cartridge {
    fn drop(&mut self) {
        // Update save file when Cartridge is dropped
        if let Err(e) = self.save_ram() {
            // Display the error but don't panic since we might
            // already be in the middle of a panic unwinding
            println!("Couldn't save: {}", e);
        }
    }
}

impl Debug for Cartridge {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let name = match self.name() {
            Some(s) => s,
            None    => "<INVALID>".to_string(),
        };

        let rombanks = self.rom_banks();

        let (rambanks, rambanksize) = match self.parse_ram_banks() {
            Some(n) => n,
            None    => (0, 0),
        };

        try!(write!(f,
                    "'{}' (Model: {}, \
                           ROM banks: {}, \
                           RAM banks: {}, \
                           RAM bank size: {}B)",
                    name, self.model.name, rombanks, rambanks, rambanksize));

        Ok(())
    }
}

// Each ROM bank is always 16KB
const ROM_BANK_SIZE: i32 = 16 * 1024;

mod offsets {
    //! Various offset values to access special memory locations within the ROM

    /// Title. Upper case ASCII 16bytes long, padded with 0s if shorter
    pub const TITLE:    usize = 0x134;
    /// Cartridge type
    pub const TYPE:     usize = 0x147;
    pub const ROM_SIZE: usize = 0x148;
    pub const RAM_SIZE: usize = 0x149;
}
<commit_msg>Create game savefile if it doesn't already exist<commit_after>//! Cartridge emulation. There are multiple cartridge types with
//! different capabilities (bankable ROM/RAM, battery, RTC etc...).

use std::fmt::{Debug, Formatter, Error};
use std::path::{Path, PathBuf};
use std::fs::{File, OpenOptions};
use std::iter::repeat;
use ascii::AsciiCast;
use std::io::{SeekFrom, Read, Write, Seek};
use std::io::Result as IoResult;

mod models;

/// Common state for all cartridge types
pub struct Cartridge {
    /// Cartridge ROM data
    rom:        Vec<u8>,
    /// Cartridge RAM data
    ram:        Vec<u8>,
    /// Total number of ROM banks in this cart
    rom_banks:  u8,
    /// Current number of the rom bank mapped at [0x4000, 0x7fff]
    rom_bank:   u8,
    /// Current bank offset for the bank mapped at [0x4000, 0x7fff].
    /// This value is added to ROM register addresses when they're in
    /// that range.
    rom_offset: i32,
    /// Current bank offset for the RAM
    ram_offset: u32,
    /// If `true` RAM is write protected
    ram_wp:     bool,
    /// Certain cartridges allow banking either the RAM or ROM
    /// depending on the value of this flag.
    bank_ram:   bool,
    /// struct used to handle model specific functions
    model:      models::Model,
    /// Path to the ROM image for this cartridge
    path:       PathBuf,
    /// optional save file used to store non-volatile RAM on emulator
    /// shutdown
    save_file:  Option<File>,
}

impl Cartridge {
    /// Load a Cartridge ROM from `path`.
    pub fn from_path(rom_path: &Path) -> IoResult<Cartridge> {
        let mut source = try!(File::open(rom_path));

        let mut rom = Vec::new();

        // There must always be at least two ROM banks
        try!((&mut source).take(2 * ROM_BANK_SIZE as u64)
             .read_to_end(&mut rom));

        let model = models::from_id(rom[offsets::TYPE]);

        let mut cartridge = Cartridge {
            rom:        rom,
            ram:        Vec::new(),
            rom_banks:  2,
            // Default to bank 1 for bankable region
            rom_bank:   1,
            rom_offset: 0,
            ram_offset: 0,
            ram_wp:     true,
            bank_ram:   false,
            model:      model,
            path:       PathBuf::from(rom_path),
            save_file:  None,
        };

        let rombanks = match cartridge.parse_rom_banks() {
            Some(n) => n,
            None    => panic!("Can't determine ROM size"),
        };

        cartridge.rom_banks = rombanks;

        // Read the remaining roms banks
        if rombanks > 2 {
            let remb      = (rombanks - 2) as usize;
            let mut off   = 2    * ROM_BANK_SIZE as usize;
            let mut remsz = remb * ROM_BANK_SIZE as usize;

            // Reserve space for the remaining banks
            cartridge.rom.extend(repeat(0).take(remsz));

            while remsz > 0 {
                let r = try!(source.read(&mut cartridge.rom[off..]));

                remsz -= r;
                off   += r;
            }
        }

        try!(cartridge.init_ram());

        Ok(cartridge)
    }

    /// Init cartridge RAM and tie it with a `File` for saving if
    /// necessary.
    fn init_ram(&mut self) -> IoResult<()> {
        let (rambanks, banksize) = match self.parse_ram_banks() {
            Some(v) => v,
            None    => panic!("Can't determine RAM size"),
        };

        let ramsize = rambanks * banksize;

        if ramsize == 0 {
            // No RAM on this cartridge, we're done
            return Ok(());
        }

        // We have some RAM, open the save file or create it if it
        // doesn't exist yet
        let mut savepath = self.path.clone();
        savepath.set_extension("sav");

        let mut save_file = try!(OpenOptions::new()
                                 .read(true)
                                 .write(true)
                                 .create(true)
                                 .open(savepath.clone()));

        let save_size = try!(save_file.metadata()).len();

        if save_size == 0 {
            // The file is empty (probably new). initialize
            // the RAM with 0s.
            self.ram = vec![0; ramsize];
            // Then fill the file with the right amount of 0s
            // to reserve enough space for saving later.
            try!(save_file.write_all(&self.ram));
        } else if save_size == (ramsize as u64) {
            // The file contains a RAM image
            try!((&mut save_file).take(ramsize as u64).read_to_end(&mut self.ram));
        } else {
            panic!("Unexpected save file size for {}: expected {} got {}",
                   savepath.display(), ramsize, save_size);
        }

        // Store the file handle to save progress later
        self.save_file = Some(save_file);

        Ok(())
    }

    /// Update the save file
    pub fn save_ram(&mut self) -> IoResult<()> {
        if let Some(mut f) = self.save_file.as_mut() {
            // Rewind to the beginning of the file and update its
            // contents
            println!("Saving non-volatile memory");

            try!(f.seek(SeekFrom::Start(0)));
            try!(f.write_all(&self.ram));
        }

        Ok(())
    }

    /// Attempt to retreive the rom's name
    pub fn name(&self) -> Option<String> {
        let mut name = String::with_capacity(16);

        for i in 0..16 {
            let c =
                match self.rom[offsets::TITLE + i].to_ascii() {
                    Ok(c) => c,
                    _     => return None,
                };

            // If the name is shorter than 16bytes it's padded with 0s
            if c.as_byte() == 0 {
                break;
            }

            // Only uppercase ASCII is valid, but let's be a little
            // more lenient
            if !c.is_print() {
                return None;
            }

            // Append new character
            name.push(c.as_char());
        }

        Some(name)
    }

    /// Return the number of ROM banks declared in the header. Each
    /// bank is 16KB.
    fn parse_rom_banks(&self) -> Option<u8> {
        let id = self.rom_byte(offsets::ROM_SIZE as u16);

        let nbanks =
            match id {
                0x00 => 2,
                0x01 => 4,
                0x02 => 8,
                0x03 => 16,
                0x04 => 32,
                0x05 => 64,
                0x06 => 128,
                0x52 => 72,
                0x53 => 80,
                0x54 => 96,
                // Unknown value
                _    => return None,
            };

        Some(nbanks)
    }

    /// Return the number of RAM banks for this ROM along with the
    /// size of each bank in bytes.
    pub fn parse_ram_banks(&self) -> Option<(usize, usize)> {

        let model = models::from_id(self.rom_byte(offsets::TYPE as u16));

        // Special case for MBC2, the RAM_SIZE field is not
        // trustworthy here (it advertises 0 banks but there's still
        // some RAM on the cartridge).
        if model.name == "MBC2" {
            // MBC2 contains 1 "bank" of 256bytes
            return Some((1, 256));
        }

        let id = self.rom_byte(offsets::RAM_SIZE as u16);

        let (nbanks, bank_size_kb) =
            match id {
                0x00 => (0,  0),
                0x01 => (1,  2),
                0x02 => (1,  8),
                0x03 => (4,  8),
                0x04 => (16, 8),
                // Unknown value
                _    => return None,
            };

        Some((nbanks, bank_size_kb * 1024))
    }

    pub fn rom_byte(&self, offset: u16) -> u8 {
        let off = offset as i32;

        if off < ROM_BANK_SIZE {
            self.rom[off as usize]
        } else {
            self.rom[(self.rom_offset + off) as usize]
        }
    }

    pub fn set_rom_byte(&mut self, offset: u16, val: u8) {
        (self.model.write_rom)(self, offset, val)
    }

    /// Return the value of RAM byte at `offset` in the currently
    /// selected RAM bank
    pub fn ram_byte(&self, offset: u16) -> u8 {
        let addr = self.ram_offset + offset as u32;

        (self.model.read_ram)(self, addr)
    }

    /// Return the value of a RAM byte at absolute address `addr`
    fn ram_byte_absolute(&self, addr: u32) -> u8 {
        *self.ram.get(addr as usize).unwrap_or(&0)
    }

    fn ram_byte_absolute_mut(&mut self, addr: u32) -> Option<&mut u8> {
        self.ram.get_mut(addr as usize)
    }

    /// Set value of RAM byte at `offset` in the curretly selected RAM
    /// bank
    pub fn set_ram_byte(&mut self, offset: u16, val: u8) {
        let addr = self.ram_offset + offset as u32;

        if self.ram_wp {
            debug!("Attempt to write to cartridge RAM while protected");
            return;
        }

        (self.model.write_ram)(self, addr, val);
    }

    /// Retreive the number of ROM banks in the cartridge
    pub fn rom_banks(&self) -> u8 {
        self.rom_banks
    }

    /// Retrieve current ROM bank number for the bankable range at
    /// [0x4000, 0x7fff]
    pub fn rom_bank(&self) -> u8 {
        self.rom_bank
    }

    /// Set new ROM bank number for the bankable range at
    /// [0x4000, 0x7fff]
    pub fn set_rom_bank(&mut self, bank: u8) {
        self.rom_bank = bank;
    }

    pub fn set_rom_offset(&mut self, offset: i32) {
        self.rom_offset = offset;
    }

    /// Enable or disable RAM write protect
    pub fn set_ram_wp(&mut self, wp: bool) {
        self.ram_wp = wp
    }

    /// Return the value of the `bank_ram` flag
    pub fn bank_ram(&self) -> bool {
        self.bank_ram
    }

    /// Set the value of the `bank_ram` flag
    pub fn set_bank_ram(&mut self, v: bool) {
        self.bank_ram = v
    }

    /// Set new RAM bank number
    pub fn set_ram_bank(&mut self, bank: u8) {
        // Bankable RAM is always 8KB per bank
        self.ram_offset = bank as u32 * 8 * 1024;
    }

    /// Create a Cartridge instance from a ROM provided in a
    /// Vec<u8>. Usefull for tests. Creates a MBC0 model without
    /// banking.
    #[cfg(test)]
    pub fn from_vec(rom: Vec<u8>) -> Cartridge {
        Cartridge {
            rom:        rom,
            ram:        Vec::new(),
            rom_bank:   1,
            rom_banks:  2,
            rom_offset: 0,
            ram_offset: 0,
            ram_wp:     true,
            bank_ram:   false,
            model:      models::from_id(0x00),
            path:       PathBuf::from("dummy"),
            save_file:  None,
        }
    }
}

impl Drop for Cartridge {
    fn drop(&mut self) {
        // Update save file when Cartridge is dropped
        if let Err(e) = self.save_ram() {
            // Display the error but don't panic since we might
            // already be in the middle of a panic unwinding
            println!("Couldn't save: {}", e);
        }
    }
}

impl Debug for Cartridge {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let name = match self.name() {
            Some(s) => s,
            None    => "<INVALID>".to_string(),
        };

        let rombanks = self.rom_banks();

        let (rambanks, rambanksize) = match self.parse_ram_banks() {
            Some(n) => n,
            None    => (0, 0),
        };

        try!(write!(f,
                    "'{}' (Model: {}, \
                           ROM banks: {}, \
                           RAM banks: {}, \
                           RAM bank size: {}B)",
                    name, self.model.name, rombanks, rambanks, rambanksize));

        Ok(())
    }
}

// Each ROM bank is always 16KB
const ROM_BANK_SIZE: i32 = 16 * 1024;

mod offsets {
    //! Various offset values to access special memory locations within the ROM

    /// Title. Upper case ASCII 16bytes long, padded with 0s if shorter
    pub const TITLE:    usize = 0x134;
    /// Cartridge type
    pub const TYPE:     usize = 0x147;
    pub const ROM_SIZE: usize = 0x148;
    pub const RAM_SIZE: usize = 0x149;
}
<|endoftext|>


<commit_before>use cgmath;
use cgmath::Matrix4;
use character::controls::CharacterInputState;
use graphics::orientation::{Orientation, Stance};
use graphics::{Dimensions, get_orientation};
use graphics::camera::CameraInputState;
use data;
use game::constants::{ASPECT_RATIO, RUN_SPRITE_OFFSET, CHARSHEET_TOTAL_WIDTH, SPRITE_OFFSET};
use shaders::{critter_pipeline, VertexData, CharacterSheet, Position, Projection};
use gfx;
use graphics::load_texture;
use gfx_app::mouse_controls::MouseInputState;
use gfx_app::{ColorFormat, DepthFormat};
use critter::{CharacterSprite, CritterData};
use specs;
use specs::{Fetch, ReadStorage, WriteStorage};

mod audio;
pub mod controls;

const SHADER_VERT: &'static [u8] = include_bytes!("../shaders/character.v.glsl");
const SHADER_FRAG: &'static [u8] = include_bytes!("../shaders/character.f.glsl");

pub struct CharacterDrawable {
  projection: Projection,
  pub position: Position,
  orientation: Orientation,
  pub stance: Stance,
  direction: Orientation,
  audio: audio::CharacterAudio,
}

impl CharacterDrawable {
  pub fn new(view: Matrix4<f32>) -> CharacterDrawable {
    CharacterDrawable {
      projection: Projection {
        model: view.into(),
        view: view.into(),
        proj: cgmath::perspective(cgmath::Deg(75.0f32), ASPECT_RATIO, 0.1, 4000.0).into(),
      },
      position: Position {
        position: [0.0, 0.0],
      },
      orientation: Orientation::Right,
      stance: Stance::Walking,
      direction: Orientation::Right,
      audio: audio::CharacterAudio::new(),
    }
  }

  pub fn update(&mut self, world_to_clip: &Projection, ci: &CharacterInputState, cs: &mut CharacterSprite, mouse_input: &MouseInputState) {
    self.projection = *world_to_clip;

    if mouse_input.left_click_point.is_some() {
      self.stance = Stance::Firing;
      self.orientation = get_orientation(mouse_input);
      if cs.character_fire_idx == 1 {
        self.audio.play_pistol();
      }
    } else {
      self.stance = Stance::Walking;
      self.orientation = ci.orientation;
    }
  }
}

impl specs::Component for CharacterDrawable {
  type Storage = specs::VecStorage<CharacterDrawable>;
}

pub struct CharacterDrawSystem<R: gfx::Resources> {
  bundle: gfx::pso::bundle::Bundle<R, critter_pipeline::Data<R>>,
  data: Vec<CritterData>,
}

impl<R: gfx::Resources> CharacterDrawSystem<R> {
  pub fn new<F>(factory: &mut F,
                rtv: gfx::handle::RenderTargetView<R, ColorFormat>,
                dsv: gfx::handle::DepthStencilView<R, DepthFormat>) -> CharacterDrawSystem<R>
    where F: gfx::Factory<R> {
    use gfx::traits::FactoryExt;

    let charter_bytes = &include_bytes!("../../assets/character.png")[..];

    let vertex_data: Vec<VertexData> =
      vec![
        VertexData::new([-20.0, -28.0, 0.0], [0.0, 1.0]),
        VertexData::new([20.0, -28.0, 0.0], [1.0, 1.0]),
        VertexData::new([20.0, 28.0, 0.0], [1.0, 0.0]),
        VertexData::new([-20.0, -28.0, 0.0], [0.0, 1.0]),
        VertexData::new([20.0, 28.0, 0.0], [1.0, 0.0]),
        VertexData::new([-20.0, 28.0, 0.0], [0.0, 0.0]),
      ];

    let (vertex_buf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ());

    let char_texture = load_texture(factory, charter_bytes).unwrap();
    let pso = factory
      .create_pipeline_simple(SHADER_VERT,
                              SHADER_FRAG,
                              critter_pipeline::new())
      .unwrap();

    let pipeline_data = critter_pipeline::Data {
      vbuf: vertex_buf,
      projection_cb: factory.create_constant_buffer(1),
      position_cb: factory.create_constant_buffer(1),
      character_sprite_cb: factory.create_constant_buffer(1),
      charactersheet: (char_texture, factory.create_sampler_linear()),
      out_color: rtv,
      out_depth: dsv,
    };

    let data = data::load_character();

    CharacterDrawSystem {
      bundle: gfx::Bundle::new(slice, pso, pipeline_data),
      data
    }
  }

  fn get_next_sprite(&self, character_idx: usize, character_fire_idx: usize, drawable: &mut CharacterDrawable) -> CharacterSheet {
    let char_sprite =
      if drawable.orientation == Orientation::Still && drawable.stance == Stance::Walking {
        let sprite_idx = (drawable.direction as usize * 28 + RUN_SPRITE_OFFSET) as usize;
        (&self.data[sprite_idx], sprite_idx)
      } else if drawable.stance == Stance::Walking {
        drawable.direction = drawable.orientation;
        let sprite_idx = (drawable.orientation as usize * 28 + character_idx + RUN_SPRITE_OFFSET) as usize;
        (&self.data[sprite_idx], sprite_idx)
      } else {
        let sprite_idx = (drawable.orientation as usize * 8 + character_fire_idx) as usize;
        (&self.data[sprite_idx], sprite_idx)
      };

    let elements_x = CHARSHEET_TOTAL_WIDTH / (char_sprite.0.data[2] + SPRITE_OFFSET);
    CharacterSheet {
      div: elements_x,
      index: char_sprite.1 as f32
    }
  }

  pub fn draw<C>(&mut self,
                 mut drawable: &mut CharacterDrawable,
                 character: &CharacterSprite,
                 encoder: &mut gfx::Encoder<R, C>)
    where C: gfx::CommandBuffer<R> {
    encoder.update_constant_buffer(&self.bundle.data.projection_cb, &drawable.projection);
    encoder.update_constant_buffer(&self.bundle.data.position_cb, &drawable.position);
    encoder.update_constant_buffer(&self.bundle.data.character_sprite_cb,
                                   &self.get_next_sprite(character.character_idx,
                                                             character.character_fire_idx,
                                                             &mut drawable));
    self.bundle.encode(encoder);
  }
}

#[derive(Debug)]
pub struct PreDrawSystem;

impl PreDrawSystem {
  pub fn new() -> PreDrawSystem {
    PreDrawSystem {}
  }
}

impl<'a> specs::System<'a> for PreDrawSystem {
  #[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
  type SystemData = (WriteStorage<'a, CharacterDrawable>,
                     ReadStorage<'a, CameraInputState>,
                     ReadStorage<'a, CharacterInputState>,
                     WriteStorage<'a, CharacterSprite>,
                     ReadStorage<'a, MouseInputState>,
                     Fetch<'a, Dimensions>);

  fn run(&mut self, (mut character, camera_input, character_input, mut character_sprite, mouse_input, dim): Self::SystemData) {
    use specs::Join;

    for (c, camera, ci, cs, mi/*, b*/) in (&mut character, &camera_input, &character_input, &mut character_sprite, &mouse_input).join() {
      let world_to_clip = dim.world_to_projection(camera);
      c.update(&world_to_clip, ci, cs, mi/*, b*/);
    }
  }
}
<commit_msg>Remove commented code<commit_after>use cgmath;
use cgmath::Matrix4;
use character::controls::CharacterInputState;
use graphics::orientation::{Orientation, Stance};
use graphics::{Dimensions, get_orientation};
use graphics::camera::CameraInputState;
use data;
use game::constants::{ASPECT_RATIO, RUN_SPRITE_OFFSET, CHARSHEET_TOTAL_WIDTH, SPRITE_OFFSET};
use shaders::{critter_pipeline, VertexData, CharacterSheet, Position, Projection};
use gfx;
use graphics::load_texture;
use gfx_app::mouse_controls::MouseInputState;
use gfx_app::{ColorFormat, DepthFormat};
use critter::{CharacterSprite, CritterData};
use specs;
use specs::{Fetch, ReadStorage, WriteStorage};

mod audio;
pub mod controls;

const SHADER_VERT: &'static [u8] = include_bytes!("../shaders/character.v.glsl");
const SHADER_FRAG: &'static [u8] = include_bytes!("../shaders/character.f.glsl");

pub struct CharacterDrawable {
  projection: Projection,
  pub position: Position,
  orientation: Orientation,
  pub stance: Stance,
  direction: Orientation,
  audio: audio::CharacterAudio,
}

impl CharacterDrawable {
  pub fn new(view: Matrix4<f32>) -> CharacterDrawable {
    CharacterDrawable {
      projection: Projection {
        model: view.into(),
        view: view.into(),
        proj: cgmath::perspective(cgmath::Deg(75.0f32), ASPECT_RATIO, 0.1, 4000.0).into(),
      },
      position: Position {
        position: [0.0, 0.0],
      },
      orientation: Orientation::Right,
      stance: Stance::Walking,
      direction: Orientation::Right,
      audio: audio::CharacterAudio::new(),
    }
  }

  pub fn update(&mut self, world_to_clip: &Projection, ci: &CharacterInputState, cs: &mut CharacterSprite, mouse_input: &MouseInputState) {
    self.projection = *world_to_clip;

    if mouse_input.left_click_point.is_some() {
      self.stance = Stance::Firing;
      self.orientation = get_orientation(mouse_input);
      if cs.character_fire_idx == 1 {
        self.audio.play_pistol();
      }
    } else {
      self.stance = Stance::Walking;
      self.orientation = ci.orientation;
    }
  }
}

impl specs::Component for CharacterDrawable {
  type Storage = specs::VecStorage<CharacterDrawable>;
}

pub struct CharacterDrawSystem<R: gfx::Resources> {
  bundle: gfx::pso::bundle::Bundle<R, critter_pipeline::Data<R>>,
  data: Vec<CritterData>,
}

impl<R: gfx::Resources> CharacterDrawSystem<R> {
  pub fn new<F>(factory: &mut F,
                rtv: gfx::handle::RenderTargetView<R, ColorFormat>,
                dsv: gfx::handle::DepthStencilView<R, DepthFormat>) -> CharacterDrawSystem<R>
    where F: gfx::Factory<R> {
    use gfx::traits::FactoryExt;

    let charter_bytes = &include_bytes!("../../assets/character.png")[..];

    let vertex_data: Vec<VertexData> =
      vec![
        VertexData::new([-20.0, -28.0, 0.0], [0.0, 1.0]),
        VertexData::new([20.0, -28.0, 0.0], [1.0, 1.0]),
        VertexData::new([20.0, 28.0, 0.0], [1.0, 0.0]),
        VertexData::new([-20.0, -28.0, 0.0], [0.0, 1.0]),
        VertexData::new([20.0, 28.0, 0.0], [1.0, 0.0]),
        VertexData::new([-20.0, 28.0, 0.0], [0.0, 0.0]),
      ];

    let (vertex_buf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ());

    let char_texture = load_texture(factory, charter_bytes).unwrap();
    let pso = factory
      .create_pipeline_simple(SHADER_VERT,
                              SHADER_FRAG,
                              critter_pipeline::new())
      .unwrap();

    let pipeline_data = critter_pipeline::Data {
      vbuf: vertex_buf,
      projection_cb: factory.create_constant_buffer(1),
      position_cb: factory.create_constant_buffer(1),
      character_sprite_cb: factory.create_constant_buffer(1),
      charactersheet: (char_texture, factory.create_sampler_linear()),
      out_color: rtv,
      out_depth: dsv,
    };

    let data = data::load_character();

    CharacterDrawSystem {
      bundle: gfx::Bundle::new(slice, pso, pipeline_data),
      data
    }
  }

  fn get_next_sprite(&self, character_idx: usize, character_fire_idx: usize, drawable: &mut CharacterDrawable) -> CharacterSheet {
    let char_sprite =
      if drawable.orientation == Orientation::Still && drawable.stance == Stance::Walking {
        let sprite_idx = (drawable.direction as usize * 28 + RUN_SPRITE_OFFSET) as usize;
        (&self.data[sprite_idx], sprite_idx)
      } else if drawable.stance == Stance::Walking {
        drawable.direction = drawable.orientation;
        let sprite_idx = (drawable.orientation as usize * 28 + character_idx + RUN_SPRITE_OFFSET) as usize;
        (&self.data[sprite_idx], sprite_idx)
      } else {
        let sprite_idx = (drawable.orientation as usize * 8 + character_fire_idx) as usize;
        (&self.data[sprite_idx], sprite_idx)
      };

    let elements_x = CHARSHEET_TOTAL_WIDTH / (char_sprite.0.data[2] + SPRITE_OFFSET);
    CharacterSheet {
      div: elements_x,
      index: char_sprite.1 as f32
    }
  }

  pub fn draw<C>(&mut self,
                 mut drawable: &mut CharacterDrawable,
                 character: &CharacterSprite,
                 encoder: &mut gfx::Encoder<R, C>)
    where C: gfx::CommandBuffer<R> {
    encoder.update_constant_buffer(&self.bundle.data.projection_cb, &drawable.projection);
    encoder.update_constant_buffer(&self.bundle.data.position_cb, &drawable.position);
    encoder.update_constant_buffer(&self.bundle.data.character_sprite_cb,
                                   &self.get_next_sprite(character.character_idx,
                                                             character.character_fire_idx,
                                                             &mut drawable));
    self.bundle.encode(encoder);
  }
}

#[derive(Debug)]
pub struct PreDrawSystem;

impl PreDrawSystem {
  pub fn new() -> PreDrawSystem {
    PreDrawSystem {}
  }
}

impl<'a> specs::System<'a> for PreDrawSystem {
  #[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
  type SystemData = (WriteStorage<'a, CharacterDrawable>,
                     ReadStorage<'a, CameraInputState>,
                     ReadStorage<'a, CharacterInputState>,
                     WriteStorage<'a, CharacterSprite>,
                     ReadStorage<'a, MouseInputState>,
                     Fetch<'a, Dimensions>);

  fn run(&mut self, (mut character, camera_input, character_input, mut character_sprite, mouse_input, dim): Self::SystemData) {
    use specs::Join;

    for (c, camera, ci, cs, mi) in (&mut character, &camera_input, &character_input, &mut character_sprite, &mouse_input).join() {
      let world_to_clip = dim.world_to_projection(camera);
      c.update(&world_to_clip, ci, cs, mi);
    }
  }
}
<|endoftext|>


<commit_before>use super::Command;

extern crate chrono;

use lib::fs::*;
use lib::io::*;
use lib::setting::*;
use self::chrono::Local;
use std::fs;
use std::path::PathBuf;

pub struct Sweep;

impl Command for Sweep {
    fn validation(&self) -> bool { true }

    fn help_message(&self) -> &'static str {
        return "sweep!";
    }

    fn main(&self) {
        println!("Sweep ...\n");

        let now  = Local::now();
        let date = now.format("%Y-%m-%d").to_string();

        let path_to_dust_box = path_buf![storage_dir(), date, "dusts"];
        create_essential_dir_all(&path_to_dust_box);

        let ignore = read_ignore_file();

        let target_files = walk_dir(".")
            .difference(&ignore)
            .cloned()
            .collect::<Vec<String>>();
        move_files_to_dust_box(target_files, &path_to_dust_box);

        move_empty_dir_to_dust_box(&path_to_dust_box);
    }
}

fn move_files_to_dust_box(target_files: Vec<String>, path_to_dust_box: &PathBuf) {
    for target in target_files.iter() {
        let target_path = path_buf![&target];
        let target_name = extract_file_name(&target_path);
        let target_base = extract_base(&target_path);
        let to          = path_buf![&path_to_dust_box, target_base];

        create_essential_dir_all(&to);

        print_with_tag(0, Tag::Execution, format!("Move \"{}\" to dust box", target_name));

        // forcedly overwrite if the file exists with same name.
        match fs::rename(target, path_buf![to, target_name]) {
            Ok(_)    => print_with_tag(1, Tag::Okay, "Moved the file to dust box"),
            Err(why) => panic!(format_with_tag(1, Tag::Error, why)),
        }
    }
}

fn move_empty_dir_to_dust_box(path_to_dust_box: &PathBuf) {
    let all_dirs = dirs_ordered_by_descending_depth(".");
    for dir in all_dirs.iter().filter(|d| *d != ".") {
        print_with_tag(0, Tag::Execution, format!("EXECUTION: Remove \"{}\" directory", dir));

        match fs::remove_dir(dir) {
            Ok(_) => {
                print_with_tag(1, Tag::Okay, "Removed the directory");
                create_essential_dir_all(&path_buf![&path_to_dust_box, dir]);
            },
            Err(why) => match why.raw_os_error() {
                Some(39) => print_with_tag(1, Tag::Notice, "The directory is not empty. Cancelled to remove it"),
                _        => panic!(format_with_tag(1, Tag::Error, why)),
            },
        }
    }
}
<commit_msg>[Refactoring] Use "&" instead of "iter()"<commit_after>use super::Command;

extern crate chrono;

use lib::fs::*;
use lib::io::*;
use lib::setting::*;
use self::chrono::Local;
use std::fs;
use std::path::PathBuf;

pub struct Sweep;

impl Command for Sweep {
    fn validation(&self) -> bool { true }

    fn help_message(&self) -> &'static str {
        return "sweep!";
    }

    fn main(&self) {
        println!("Sweep ...\n");

        let now  = Local::now();
        let date = now.format("%Y-%m-%d").to_string();

        let path_to_dust_box = path_buf![storage_dir(), date, "dusts"];
        create_essential_dir_all(&path_to_dust_box);

        let ignore = read_ignore_file();

        let target_files = walk_dir(".")
            .difference(&ignore)
            .cloned()
            .collect::<Vec<String>>();
        move_files_to_dust_box(target_files, &path_to_dust_box);

        move_empty_dir_to_dust_box(&path_to_dust_box);
    }
}

fn move_files_to_dust_box(target_files: Vec<String>, path_to_dust_box: &PathBuf) {
    for target in &target_files {
        let target_path = path_buf![&target];
        let target_name = extract_file_name(&target_path);
        let target_base = extract_base(&target_path);
        let to          = path_buf![&path_to_dust_box, target_base];

        create_essential_dir_all(&to);

        print_with_tag(0, Tag::Execution, format!("Move \"{}\" to dust box", target_name));

        // forcedly overwrite if the file exists with same name.
        match fs::rename(target, path_buf![to, target_name]) {
            Ok(_)    => print_with_tag(1, Tag::Okay, "Moved the file to dust box"),
            Err(why) => panic!(format_with_tag(1, Tag::Error, why)),
        }
    }
}

fn move_empty_dir_to_dust_box(path_to_dust_box: &PathBuf) {
    let all_dirs = dirs_ordered_by_descending_depth(".");
    for dir in all_dirs.iter().filter(|d| *d != ".") {
        print_with_tag(0, Tag::Execution, format!("EXECUTION: Remove \"{}\" directory", dir));

        match fs::remove_dir(dir) {
            Ok(_) => {
                print_with_tag(1, Tag::Okay, "Removed the directory");
                create_essential_dir_all(&path_buf![&path_to_dust_box, dir]);
            },
            Err(why) => match why.raw_os_error() {
                Some(39) => print_with_tag(1, Tag::Notice, "The directory is not empty. Cancelled to remove it"),
                _        => panic!(format_with_tag(1, Tag::Error, why)),
            },
        }
    }
}
<|endoftext|>


<commit_before>use std::cmp;

use bytes::Bytes;

use crate::error;

use crate::solicit::end_stream::EndStream;
use crate::solicit::header::Headers;
use crate::solicit::session::StreamState;
use crate::solicit::WindowSize;

use super::types::Types;

use super::stream_queue::StreamQueue;
use super::window_size;
use crate::common::stream_handler::StreamHandlerInternal;
use crate::data_or_headers::DataOrHeaders;
use crate::data_or_headers_with_flag::DataOrHeadersWithFlag;
use crate::ErrorCode;

pub enum HttpStreamCommand {
    Headers(Headers, EndStream),
    Data(Bytes, EndStream),
    Rst(ErrorCode),
}

impl HttpStreamCommand {
    pub fn from(part: DataOrHeadersWithFlag) -> HttpStreamCommand {
        let end_stream = match part.last {
            true => EndStream::Yes,
            false => EndStream::No,
        };
        match part.content {
            DataOrHeaders::Data(data) => HttpStreamCommand::Data(data, end_stream),
            DataOrHeaders::Headers(headers) => HttpStreamCommand::Headers(headers, end_stream),
        }
    }
}

#[must_use]
pub struct DroppedData {
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct HttpStreamStateSnapshot {
    pub state: StreamState,
    pub out_window_size: i32,
    pub in_window_size: i32,
    pub pump_out_window_size: isize,
    pub queued_out_data_size: usize,
    pub out_data_size: usize,
}

#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum InMessageStage {
    Initial,
    AfterInitialHeaders,
    AfterTrailingHeaders,
}

/// All HTTP/2 stream state.
/// Note the state must be kept in sync with other fields,
/// thus sometimes this object must be manipulated with `HttpStreamRef`.
pub(crate) struct HttpStreamCommon<T: Types> {
    pub specific: T::HttpStreamSpecific,
    pub state: StreamState,
    pub out_window_size: WindowSize,
    pub in_window_size: WindowSize,
    pub outgoing: StreamQueue,
    pub peer_tx: Option<T::StreamHandlerHolder>,
    // task waiting for window increase
    pub pump_out_window: window_size::StreamOutWindowSender,
    // Incoming remaining content-length
    pub in_rem_content_length: Option<u64>,
    pub in_message_stage: InMessageStage,
}

impl<T: Types> HttpStreamCommon<T> {
    pub fn new(
        in_window_size: u32,
        out_window_size: u32,
        pump_out_window: window_size::StreamOutWindowSender,
        in_rem_content_length: Option<u64>,
        in_message_stage: InMessageStage,
        specific: T::HttpStreamSpecific,
    ) -> HttpStreamCommon<T> {
        HttpStreamCommon {
            specific,
            state: StreamState::Open,
            in_window_size: WindowSize::new(in_window_size as i32),
            out_window_size: WindowSize::new(out_window_size as i32),
            outgoing: StreamQueue::new(),
            peer_tx: None,
            pump_out_window,
            in_rem_content_length,
            in_message_stage,
        }
    }

    pub fn snapshot(&self) -> HttpStreamStateSnapshot {
        HttpStreamStateSnapshot {
            state: self.state,
            out_window_size: self.out_window_size.0,
            in_window_size: self.in_window_size.0,
            pump_out_window_size: self.pump_out_window.get(),
            queued_out_data_size: self.outgoing.data_size(),
            out_data_size: self.outgoing.data_size(),
        }
    }

    pub fn close_local(&mut self) {
        trace!("close local");
        self.state = match self.state {
            StreamState::Closed | StreamState::HalfClosedRemote => StreamState::Closed,
            _ => StreamState::HalfClosedLocal,
        };
    }

    pub fn close_remote(&mut self) {
        trace!("close remote");
        self.state = match self.state {
            StreamState::Closed | StreamState::HalfClosedLocal => StreamState::Closed,
            _ => StreamState::HalfClosedRemote,
        };
    }

    pub fn conn_died(mut self, error: error::Error) {
        if let Some(handler) = self.peer_tx.take() {
            drop(handler.error(error));
        }
    }

    /// Must be kept in sync with `pop_outg`.
    pub fn is_writable(&self) -> bool {
        match self.outgoing.front() {
            Some(front) => match front {
                DataOrHeaders::Headers(..) => true,
                DataOrHeaders::Data(data) => data.len() == 0 || self.out_window_size.size() != 0,
            },
            None => {
                if let Some(_error_code) = self.outgoing.end() {
                    if !self.state.is_closed_local() {
                        return true;
                    }
                };

                false
            }
        }
    }

    #[cfg(debug_assertions)]
    pub fn pop_outg(&mut self, conn_out_window_size: &mut WindowSize) -> Option<HttpStreamCommand> {
        let writable = self.is_writable();
        let conn_out_window_size_before = conn_out_window_size.0;

        let command = self.pop_outg_impl(conn_out_window_size);
        if command.is_some() {
            assert!(writable);
        } else {
            assert!(
                !writable || conn_out_window_size_before == 0,
                "popped nothing but writable: {}, conn out window size before: {}, {:?}",
                writable,
                conn_out_window_size_before,
                self.snapshot()
            );
        }
        command
    }

    #[cfg(not(debug_assertions))]
    pub fn pop_outg(&mut self, conn_out_window_size: &mut WindowSize) -> Option<HttpStreamCommand> {
        self.pop_outg_impl(conn_out_window_size)
    }

    fn pop_outg_impl(
        &mut self,
        conn_out_window_size: &mut WindowSize,
    ) -> Option<HttpStreamCommand> {
        if self.outgoing.is_empty() {
            return if let Some(error_code) = self.outgoing.end() {
                if self.state.is_closed_local() {
                    None
                } else {
                    self.close_local();
                    Some(match error_code {
                        ErrorCode::NoError => HttpStreamCommand::Data(Bytes::new(), EndStream::Yes),
                        error_code => HttpStreamCommand::Rst(error_code),
                    })
                }
            } else {
                None
            };
        }

        let pop_headers = if let &DataOrHeaders::Headers(..) = self.outgoing.front().unwrap() {
            true
        } else {
            false
        };
        if pop_headers {
            let r = self.outgoing.pop_front().unwrap();
            let last = self.outgoing.end() == Some(ErrorCode::NoError);
            if last {
                self.close_local();
            }
            return Some(HttpStreamCommand::from(DataOrHeadersWithFlag {
                content: r,
                last: last,
            }));
        }

        if self.out_window_size.size() <= 0 || conn_out_window_size.size() <= 0 {
            return None;
        }

        let mut data = if let Some(DataOrHeaders::Data(data)) = self.outgoing.pop_front() {
            data
        } else {
            unreachable!()
        };

        // Min of connection and stream window size
        let max_window = cmp::min(self.out_window_size.size(), conn_out_window_size.size());

        if data.len() as usize > max_window as usize {
            trace!("truncating data of len {} to {}", data.len(), max_window);
            let size = max_window as usize;
            let rem = data.split_off(size);
            self.outgoing.push_front(DataOrHeaders::Data(rem));
        };

        self.out_window_size
            .try_decrease_to_positive(data.len() as i32)
            .unwrap();
        conn_out_window_size
            .try_decrease_to_positive(data.len() as i32)
            .unwrap();

        let last = self.outgoing.end() == Some(ErrorCode::NoError);
        if last {
            self.close_local();
        }

        Some(HttpStreamCommand::from(DataOrHeadersWithFlag {
            content: DataOrHeaders::Data(data),
            last: last,
        }))
    }

    pub fn data_recvd(&mut self, data: Bytes, last: bool) {
        if let Some(ref mut response_handler) = self.peer_tx {
            // TODO: reset stream if rx is dead
            drop(response_handler.data_frame(data, last));
        }
    }

    pub fn rst_recvd(&mut self, error_code: ErrorCode) -> DroppedData {
        if let Some(response_handler) = self.peer_tx.take() {
            drop(response_handler.rst(error_code));
        }
        DroppedData {
            size: self.outgoing.data_size(),
        }
    }

    pub fn goaway_recvd(&mut self, _raw_error_code: u32) {
        if let Some(response_handler) = self.peer_tx.take() {
            // it is OK to ignore error: handler may be already dead
            drop(response_handler.error(error::Error::GoawayReceived));
        }
    }
}

pub(crate) trait HttpStreamDataSpecific: Send + 'static {}

pub(crate) trait HttpStreamData {
    type Types: Types;
}
<commit_msg>Fix h2spec test http2/6.9.2<commit_after>use std::cmp;

use bytes::Bytes;

use crate::error;

use crate::solicit::end_stream::EndStream;
use crate::solicit::header::Headers;
use crate::solicit::session::StreamState;
use crate::solicit::WindowSize;

use super::types::Types;

use super::stream_queue::StreamQueue;
use super::window_size;
use crate::common::stream_handler::StreamHandlerInternal;
use crate::data_or_headers::DataOrHeaders;
use crate::data_or_headers_with_flag::DataOrHeadersWithFlag;
use crate::ErrorCode;

pub enum HttpStreamCommand {
    Headers(Headers, EndStream),
    Data(Bytes, EndStream),
    Rst(ErrorCode),
}

impl HttpStreamCommand {
    pub fn from(part: DataOrHeadersWithFlag) -> HttpStreamCommand {
        let end_stream = match part.last {
            true => EndStream::Yes,
            false => EndStream::No,
        };
        match part.content {
            DataOrHeaders::Data(data) => HttpStreamCommand::Data(data, end_stream),
            DataOrHeaders::Headers(headers) => HttpStreamCommand::Headers(headers, end_stream),
        }
    }
}

#[must_use]
pub struct DroppedData {
    pub size: usize,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct HttpStreamStateSnapshot {
    pub state: StreamState,
    pub out_window_size: i32,
    pub in_window_size: i32,
    pub pump_out_window_size: isize,
    pub queued_out_data_size: usize,
    pub out_data_size: usize,
}

#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum InMessageStage {
    Initial,
    AfterInitialHeaders,
    AfterTrailingHeaders,
}

/// All HTTP/2 stream state.
/// Note the state must be kept in sync with other fields,
/// thus sometimes this object must be manipulated with `HttpStreamRef`.
pub(crate) struct HttpStreamCommon<T: Types> {
    pub specific: T::HttpStreamSpecific,
    pub state: StreamState,
    pub out_window_size: WindowSize,
    pub in_window_size: WindowSize,
    pub outgoing: StreamQueue,
    pub peer_tx: Option<T::StreamHandlerHolder>,
    // task waiting for window increase
    pub pump_out_window: window_size::StreamOutWindowSender,
    // Incoming remaining content-length
    pub in_rem_content_length: Option<u64>,
    pub in_message_stage: InMessageStage,
}

impl<T: Types> HttpStreamCommon<T> {
    pub fn new(
        in_window_size: u32,
        out_window_size: u32,
        pump_out_window: window_size::StreamOutWindowSender,
        in_rem_content_length: Option<u64>,
        in_message_stage: InMessageStage,
        specific: T::HttpStreamSpecific,
    ) -> HttpStreamCommon<T> {
        HttpStreamCommon {
            specific,
            state: StreamState::Open,
            in_window_size: WindowSize::new(in_window_size as i32),
            out_window_size: WindowSize::new(out_window_size as i32),
            outgoing: StreamQueue::new(),
            peer_tx: None,
            pump_out_window,
            in_rem_content_length,
            in_message_stage,
        }
    }

    pub fn snapshot(&self) -> HttpStreamStateSnapshot {
        HttpStreamStateSnapshot {
            state: self.state,
            out_window_size: self.out_window_size.0,
            in_window_size: self.in_window_size.0,
            pump_out_window_size: self.pump_out_window.get(),
            queued_out_data_size: self.outgoing.data_size(),
            out_data_size: self.outgoing.data_size(),
        }
    }

    pub fn close_local(&mut self) {
        trace!("close local");
        self.state = match self.state {
            StreamState::Closed | StreamState::HalfClosedRemote => StreamState::Closed,
            _ => StreamState::HalfClosedLocal,
        };
    }

    pub fn close_remote(&mut self) {
        trace!("close remote");
        self.state = match self.state {
            StreamState::Closed | StreamState::HalfClosedLocal => StreamState::Closed,
            _ => StreamState::HalfClosedRemote,
        };
    }

    pub fn conn_died(mut self, error: error::Error) {
        if let Some(handler) = self.peer_tx.take() {
            drop(handler.error(error));
        }
    }

    /// Must be kept in sync with `pop_outg`.
    pub fn is_writable(&self) -> bool {
        match self.outgoing.front() {
            Some(front) => match front {
                DataOrHeaders::Headers(..) => true,
                DataOrHeaders::Data(data) => data.len() == 0 || self.out_window_size.size() > 0,
            },
            None => {
                if let Some(_error_code) = self.outgoing.end() {
                    if !self.state.is_closed_local() {
                        return true;
                    }
                };

                false
            }
        }
    }

    #[cfg(debug_assertions)]
    pub fn pop_outg(&mut self, conn_out_window_size: &mut WindowSize) -> Option<HttpStreamCommand> {
        let writable = self.is_writable();
        let conn_out_window_size_before = conn_out_window_size.0;

        let command = self.pop_outg_impl(conn_out_window_size);
        if command.is_some() {
            assert!(writable);
        } else {
            assert!(
                !writable || conn_out_window_size_before == 0,
                "popped nothing but writable: {}, conn out window size before: {}, {:?}",
                writable,
                conn_out_window_size_before,
                self.snapshot()
            );
        }
        command
    }

    #[cfg(not(debug_assertions))]
    pub fn pop_outg(&mut self, conn_out_window_size: &mut WindowSize) -> Option<HttpStreamCommand> {
        self.pop_outg_impl(conn_out_window_size)
    }

    fn pop_outg_impl(
        &mut self,
        conn_out_window_size: &mut WindowSize,
    ) -> Option<HttpStreamCommand> {
        if self.outgoing.is_empty() {
            return if let Some(error_code) = self.outgoing.end() {
                if self.state.is_closed_local() {
                    None
                } else {
                    self.close_local();
                    Some(match error_code {
                        ErrorCode::NoError => HttpStreamCommand::Data(Bytes::new(), EndStream::Yes),
                        error_code => HttpStreamCommand::Rst(error_code),
                    })
                }
            } else {
                None
            };
        }

        let pop_headers = if let &DataOrHeaders::Headers(..) = self.outgoing.front().unwrap() {
            true
        } else {
            false
        };
        if pop_headers {
            let r = self.outgoing.pop_front().unwrap();
            let last = self.outgoing.end() == Some(ErrorCode::NoError);
            if last {
                self.close_local();
            }
            return Some(HttpStreamCommand::from(DataOrHeadersWithFlag {
                content: r,
                last: last,
            }));
        }

        if self.out_window_size.size() <= 0 || conn_out_window_size.size() <= 0 {
            return None;
        }

        let mut data = if let Some(DataOrHeaders::Data(data)) = self.outgoing.pop_front() {
            data
        } else {
            unreachable!()
        };

        // Min of connection and stream window size
        let max_window = cmp::min(self.out_window_size.size(), conn_out_window_size.size());

        if data.len() as usize > max_window as usize {
            trace!("truncating data of len {} to {}", data.len(), max_window);
            let size = max_window as usize;
            let rem = data.split_off(size);
            self.outgoing.push_front(DataOrHeaders::Data(rem));
        };

        self.out_window_size
            .try_decrease_to_positive(data.len() as i32)
            .unwrap();
        conn_out_window_size
            .try_decrease_to_positive(data.len() as i32)
            .unwrap();

        let last = self.outgoing.end() == Some(ErrorCode::NoError);
        if last {
            self.close_local();
        }

        Some(HttpStreamCommand::from(DataOrHeadersWithFlag {
            content: DataOrHeaders::Data(data),
            last: last,
        }))
    }

    pub fn data_recvd(&mut self, data: Bytes, last: bool) {
        if let Some(ref mut response_handler) = self.peer_tx {
            // TODO: reset stream if rx is dead
            drop(response_handler.data_frame(data, last));
        }
    }

    pub fn rst_recvd(&mut self, error_code: ErrorCode) -> DroppedData {
        if let Some(response_handler) = self.peer_tx.take() {
            drop(response_handler.rst(error_code));
        }
        DroppedData {
            size: self.outgoing.data_size(),
        }
    }

    pub fn goaway_recvd(&mut self, _raw_error_code: u32) {
        if let Some(response_handler) = self.peer_tx.take() {
            // it is OK to ignore error: handler may be already dead
            drop(response_handler.error(error::Error::GoawayReceived));
        }
    }
}

pub(crate) trait HttpStreamDataSpecific: Send + 'static {}

pub(crate) trait HttpStreamData {
    type Types: Types;
}
<|endoftext|>


<commit_before>#![feature(unsafe_destructor)]

extern crate "lua52-sys" as ffi;
extern crate libc;

use std::ffi::{CStr, CString};
use std::io::Error as IoError;
use std::borrow::Borrow;
use std::marker::PhantomData;

pub use functions_read::LuaFunction;
pub use lua_tables::LuaTable;

pub mod any;
pub mod functions_read;
pub mod lua_tables;
//pub mod userdata;

mod functions_write;
mod rust_tables;
mod values;
mod tuples;

/// Main object of the library.
///
/// The lifetime parameter corresponds to the lifetime of the content of the Lua context.
pub struct Lua<'lua> {
    lua: LuaContext,
    must_be_closed: bool,
    marker: PhantomData<&'lua ()>,
}

///
pub struct PushGuard<L> where L: AsMutLua {
    lua: L,
    size: i32,
}

/// Trait for objects that have access to a Lua context.
pub unsafe trait AsLua {
    fn as_lua(&self) -> LuaContext;
}

/// Trait for objects that have access to a Lua context.
pub unsafe trait AsMutLua: AsLua {
    fn as_mut_lua(&mut self) -> LuaContext;
}

/// Represents a raw Lua context.
#[derive(Copy, Clone)]
#[allow(raw_pointer_derive)]
pub struct LuaContext(*mut ffi::lua_State);
unsafe impl Send for LuaContext {}

unsafe impl<'a, 'lua> AsLua for &'a Lua<'lua> {
    fn as_lua(&self) -> LuaContext {
        self.lua
    }
}

unsafe impl<'a, 'lua> AsLua for &'a mut Lua<'lua> {
    fn as_lua(&self) -> LuaContext {
        self.lua
    }
}

unsafe impl<'a, 'lua> AsMutLua for &'a mut Lua<'lua> {
    fn as_mut_lua(&mut self) -> LuaContext {
        self.lua
    }
}

unsafe impl<L> AsLua for PushGuard<L> where L: AsMutLua {
    fn as_lua(&self) -> LuaContext {
        self.lua.as_lua()
    }
}

unsafe impl<L> AsMutLua for PushGuard<L> where L: AsMutLua {
    fn as_mut_lua(&mut self) -> LuaContext {
        self.lua.as_mut_lua()
    }
}

unsafe impl<'a, L> AsLua for &'a L where L: AsLua {
    fn as_lua(&self) -> LuaContext {
        (**self).as_lua()
    }
}

unsafe impl<'a, L> AsLua for &'a mut L where L: AsLua {
    fn as_lua(&self) -> LuaContext {
        (**self).as_lua()
    }
}

unsafe impl<'a, L> AsMutLua for &'a mut L where L: AsMutLua {
    fn as_mut_lua(&mut self) -> LuaContext {
        (**self).as_mut_lua()
    }
}

/// Should be implemented by whatever type is pushable on the Lua stack.
pub trait Push<L> where L: AsMutLua {
    /// Pushes the value on the top of the stack.
    /// Must return the number of elements pushed.
    ///
    /// You can implement this for any type you want by redirecting to call to
    /// another implementation (for example `5.push_to_lua`) or by calling `userdata::push_userdata`
    fn push_to_lua(self, lua: L) -> PushGuard<L>;
}

/// Reads the data from Lua.
pub trait LuaRead<L>: Sized where L: AsLua {
    /// Reads the data from Lua.
    fn lua_read(lua: L) -> Option<Self> {
        LuaRead::lua_read_at_position(lua, -1)
    }

    /// Reads the data from Lua.
    fn lua_read_at_position(lua: L, index: i32) -> Option<Self>;
}

/// Error that can happen when executing Lua code.
#[derive(Debug)]
pub enum LuaError {
    /// There was a syntax error when parsing the Lua code.
    SyntaxError(String),

    /// There was an error during execution of the Lua code
    /// (for example not enough parameters for a function call).
    ExecutionError(String),

    /// There was an IoError while reading the source code to execute.
    ReadError(IoError),

    /// The call to `execute` has requested the wrong type of data.
    WrongType,
}

impl<'lua> Lua<'lua> {
    /// Builds a new Lua context.
    ///
    /// # Panic
    ///
    /// The function panics if the underlying call to `lua_newstate` fails
    /// (which indicates lack of memory).
    pub fn new() -> Lua<'lua> {
        let lua = unsafe { ffi::lua_newstate(alloc, std::ptr::null_mut()) };
        if lua.is_null() {
            panic!("lua_newstate failed");
        }

        // this alloc function is required to create a lua state.
        extern "C" fn alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
                            nsize: libc::size_t) -> *mut libc::c_void
        {
            unsafe {
                if nsize == 0 {
                    libc::free(ptr as *mut libc::c_void);
                    std::ptr::null_mut()
                } else {
                    libc::realloc(ptr, nsize)
                }
            }
        }

        // called whenever lua encounters an unexpected error.
        extern "C" fn panic(lua: *mut ffi::lua_State) -> libc::c_int {
            let err = unsafe { ffi::lua_tostring(lua, -1) };
            let err = unsafe { CStr::from_ptr(err) };
            let err = String::from_utf8(err.to_bytes().to_vec()).unwrap();
            panic!("PANIC: unprotected error in call to Lua API ({})\n", err);
        }

        unsafe { ffi::lua_atpanic(lua, panic) };

        Lua {
            lua: LuaContext(lua),
            must_be_closed: true,
            marker: PhantomData,
        }
    }

    /// Takes an existing lua_State and build a Lua object from it.
    ///
    /// # Arguments
    ///  * close_at_the_end: if true, lua_close will be called on the lua_State on the destructor
    pub unsafe fn from_existing_state<T>(lua: *mut T, close_at_the_end: bool) -> Lua<'lua> {
        Lua {
            lua: std::mem::transmute(lua),
            must_be_closed: close_at_the_end,
            marker: PhantomData,
        }
    }

    /// Opens all standard Lua libraries.
    /// This is done by calling `luaL_openlibs`.
    pub fn openlibs(&mut self) {
        unsafe { ffi::luaL_openlibs(self.lua.0) }
    }

    /*/// Executes some Lua code on the context.
    pub fn execute<'a, T: CopyRead<LoadedVariable<'a, Lua<'lua>>>>(&'a mut self, code: &str) -> Result<T, LuaError> {
        let mut f = try!(functions_read::LuaFunction::load(self, code));
        f.call()
    }

    /// Executes some Lua code on the context.
    pub fn execute_from_reader<'a, T: CopyRead<LoadedVariable<'a, Lua<'lua>>>, R: std::io::Reader + 'static>(&'a mut self, code: R) -> Result<T, LuaError> {
        let mut f = try!(functions_read::LuaFunction::load_from_reader(self, code));
        f.call()
    }*/

    /// Reads the value of a global variable by copying it.
    pub fn get<'l, I, V>(&'l mut self, index: I) -> Option<V>
                         where I: Borrow<str>, V: LuaRead<&'l mut Lua<'lua>>
    {
        let index = CString::new(index.borrow()).unwrap();
        unsafe { ffi::lua_getglobal(self.lua.0, index.as_ptr()); }
        LuaRead::lua_read(self)
    }

    /// Modifies the value of a global variable.
    pub fn set<'a, I, V>(&'a mut self, index: I, value: V)
                         where I: Borrow<str>, V: Push<&'a mut Lua<'lua>>
    {
        let index = CString::new(index.borrow()).unwrap();
        let guard = value.push_to_lua(self);
        unsafe { ffi::lua_setglobal(self.lua.0, index.as_ptr()); }
        unsafe { std::mem::forget(guard) }
    }
}

#[unsafe_destructor]
impl<'lua> Drop for Lua<'lua> {
    fn drop(&mut self) {
        if self.must_be_closed {
            unsafe { ffi::lua_close(self.lua.0) }
        }
    }
}

#[unsafe_destructor]
impl<L> Drop for PushGuard<L> where L: AsMutLua {
    fn drop(&mut self) {
        unsafe { ffi::lua_pop(self.lua.as_mut_lua().0, self.size); }
    }
}
<commit_msg>Restore execute and execute_from_read in Lua<commit_after>#![feature(unsafe_destructor)]

extern crate "lua52-sys" as ffi;
extern crate libc;

use std::ffi::{CStr, CString};
use std::io::Read;
use std::io::Error as IoError;
use std::borrow::Borrow;
use std::marker::PhantomData;

pub use functions_read::LuaFunction;
pub use lua_tables::LuaTable;

pub mod any;
pub mod functions_read;
pub mod lua_tables;
//pub mod userdata;

mod functions_write;
mod rust_tables;
mod values;
mod tuples;

/// Main object of the library.
///
/// The lifetime parameter corresponds to the lifetime of the content of the Lua context.
pub struct Lua<'lua> {
    lua: LuaContext,
    must_be_closed: bool,
    marker: PhantomData<&'lua ()>,
}

///
pub struct PushGuard<L> where L: AsMutLua {
    lua: L,
    size: i32,
}

/// Trait for objects that have access to a Lua context.
pub unsafe trait AsLua {
    fn as_lua(&self) -> LuaContext;
}

/// Trait for objects that have access to a Lua context.
pub unsafe trait AsMutLua: AsLua {
    fn as_mut_lua(&mut self) -> LuaContext;
}

/// Represents a raw Lua context.
#[derive(Copy, Clone)]
#[allow(raw_pointer_derive)]
pub struct LuaContext(*mut ffi::lua_State);
unsafe impl Send for LuaContext {}

unsafe impl<'a, 'lua> AsLua for &'a Lua<'lua> {
    fn as_lua(&self) -> LuaContext {
        self.lua
    }
}

unsafe impl<'a, 'lua> AsLua for &'a mut Lua<'lua> {
    fn as_lua(&self) -> LuaContext {
        self.lua
    }
}

unsafe impl<'a, 'lua> AsMutLua for &'a mut Lua<'lua> {
    fn as_mut_lua(&mut self) -> LuaContext {
        self.lua
    }
}

unsafe impl<L> AsLua for PushGuard<L> where L: AsMutLua {
    fn as_lua(&self) -> LuaContext {
        self.lua.as_lua()
    }
}

unsafe impl<L> AsMutLua for PushGuard<L> where L: AsMutLua {
    fn as_mut_lua(&mut self) -> LuaContext {
        self.lua.as_mut_lua()
    }
}

unsafe impl<'a, L> AsLua for &'a L where L: AsLua {
    fn as_lua(&self) -> LuaContext {
        (**self).as_lua()
    }
}

unsafe impl<'a, L> AsLua for &'a mut L where L: AsLua {
    fn as_lua(&self) -> LuaContext {
        (**self).as_lua()
    }
}

unsafe impl<'a, L> AsMutLua for &'a mut L where L: AsMutLua {
    fn as_mut_lua(&mut self) -> LuaContext {
        (**self).as_mut_lua()
    }
}

/// Should be implemented by whatever type is pushable on the Lua stack.
pub trait Push<L> where L: AsMutLua {
    /// Pushes the value on the top of the stack.
    /// Must return the number of elements pushed.
    ///
    /// You can implement this for any type you want by redirecting to call to
    /// another implementation (for example `5.push_to_lua`) or by calling `userdata::push_userdata`
    fn push_to_lua(self, lua: L) -> PushGuard<L>;
}

/// Reads the data from Lua.
pub trait LuaRead<L>: Sized where L: AsLua {
    /// Reads the data from Lua.
    fn lua_read(lua: L) -> Option<Self> {
        LuaRead::lua_read_at_position(lua, -1)
    }

    /// Reads the data from Lua.
    fn lua_read_at_position(lua: L, index: i32) -> Option<Self>;
}

/// Error that can happen when executing Lua code.
#[derive(Debug)]
pub enum LuaError {
    /// There was a syntax error when parsing the Lua code.
    SyntaxError(String),

    /// There was an error during execution of the Lua code
    /// (for example not enough parameters for a function call).
    ExecutionError(String),

    /// There was an IoError while reading the source code to execute.
    ReadError(IoError),

    /// The call to `execute` has requested the wrong type of data.
    WrongType,
}

impl<'lua> Lua<'lua> {
    /// Builds a new Lua context.
    ///
    /// # Panic
    ///
    /// The function panics if the underlying call to `lua_newstate` fails
    /// (which indicates lack of memory).
    pub fn new() -> Lua<'lua> {
        let lua = unsafe { ffi::lua_newstate(alloc, std::ptr::null_mut()) };
        if lua.is_null() {
            panic!("lua_newstate failed");
        }

        // this alloc function is required to create a lua state.
        extern "C" fn alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
                            nsize: libc::size_t) -> *mut libc::c_void
        {
            unsafe {
                if nsize == 0 {
                    libc::free(ptr as *mut libc::c_void);
                    std::ptr::null_mut()
                } else {
                    libc::realloc(ptr, nsize)
                }
            }
        }

        // called whenever lua encounters an unexpected error.
        extern "C" fn panic(lua: *mut ffi::lua_State) -> libc::c_int {
            let err = unsafe { ffi::lua_tostring(lua, -1) };
            let err = unsafe { CStr::from_ptr(err) };
            let err = String::from_utf8(err.to_bytes().to_vec()).unwrap();
            panic!("PANIC: unprotected error in call to Lua API ({})\n", err);
        }

        unsafe { ffi::lua_atpanic(lua, panic) };

        Lua {
            lua: LuaContext(lua),
            must_be_closed: true,
            marker: PhantomData,
        }
    }

    /// Takes an existing lua_State and build a Lua object from it.
    ///
    /// # Arguments
    ///  * close_at_the_end: if true, lua_close will be called on the lua_State on the destructor
    pub unsafe fn from_existing_state<T>(lua: *mut T, close_at_the_end: bool) -> Lua<'lua> {
        Lua {
            lua: std::mem::transmute(lua),
            must_be_closed: close_at_the_end,
            marker: PhantomData,
        }
    }

    /// Opens all standard Lua libraries.
    /// This is done by calling `luaL_openlibs`.
    pub fn openlibs(&mut self) {
        unsafe { ffi::luaL_openlibs(self.lua.0) }
    }

    /// Executes some Lua code on the context.
    pub fn execute<'a, T>(&'a mut self, code: &str) -> Result<T, LuaError> where T: for<'g> LuaRead<&'g mut PushGuard<&'a mut Lua<'lua>>> {
        let mut f = try!(functions_read::LuaFunction::load(self, code));
        f.call()
    }

    /// Executes some Lua code on the context.
    pub fn execute_from_reader<'a, T, R: Read + 'static>(&'a mut self, code: R) -> Result<T, LuaError> where T: for<'g> LuaRead<&'g mut PushGuard<&'a mut Lua<'lua>>> {
        let mut f = try!(functions_read::LuaFunction::load_from_reader(self, code));
        f.call()
    }

    /// Reads the value of a global variable by copying it.
    pub fn get<'l, I, V>(&'l mut self, index: I) -> Option<V>
                         where I: Borrow<str>, V: LuaRead<&'l mut Lua<'lua>>
    {
        let index = CString::new(index.borrow()).unwrap();
        unsafe { ffi::lua_getglobal(self.lua.0, index.as_ptr()); }
        LuaRead::lua_read(self)
    }

    /// Modifies the value of a global variable.
    pub fn set<'a, I, V>(&'a mut self, index: I, value: V)
                         where I: Borrow<str>, V: Push<&'a mut Lua<'lua>>
    {
        let index = CString::new(index.borrow()).unwrap();
        let guard = value.push_to_lua(self);
        unsafe { ffi::lua_setglobal(self.lua.0, index.as_ptr()); }
        unsafe { std::mem::forget(guard) }
    }
}

#[unsafe_destructor]
impl<'lua> Drop for Lua<'lua> {
    fn drop(&mut self) {
        if self.must_be_closed {
            unsafe { ffi::lua_close(self.lua.0) }
        }
    }
}

#[unsafe_destructor]
impl<L> Drop for PushGuard<L> where L: AsMutLua {
    fn drop(&mut self) {
        unsafe { ffi::lua_pop(self.lua.as_mut_lua().0, self.size); }
    }
}
<|endoftext|>


<commit_before>use std::io;
use std::io::prelude::*;
use std::char;
use std::collections::HashMap;

fn part1_next(n: u32, d: char) -> u32 {
    match d {
        'U' if n > 3 => n - 3,
        'D' if n < 7 => n + 3,
        'L' if n % 3 != 1 => n - 1,
        'R' if n % 3 != 0 => n + 1,
        _ => n,
    }
}

#[cfg_attr(rustfmt, rustfmt_skip)]
const P2_KEYPAD: &'static [((i8, i8), char)] = &[
                            ((2,4), '1'),
              ((1,3), '2'), ((2,3), '3'), ((3,3), '4'),
((0,2), '5'), ((1,2), '6'), ((2,2), '7'), ((3,2), '8'), ((4,2), '9'),
              ((1,1), 'A'), ((2,1), 'B'), ((3,1), 'C'),
                            ((2,0), 'D')
];

#[cfg_attr(rustfmt, rustfmt_skip)]
fn translate_move(d: char) -> (i8, i8) {

    match d {
        'U' => ( 0,  1),
        'D' => ( 0, -1),
        'R' => ( 1,  0),
        'L' => (-1,  0),
        _ => panic!("invalid input"),
    }
}

fn main() {
    let mut part1 = String::new();
    let mut part2 = String::new();
    let mut p1 = 5;
    let mut p2_cur = (0, 2); // start at the coordinate of '5'

    let keypad: HashMap<(i8, i8), char> = P2_KEYPAD.iter().map(|&i| i).collect();
    let step = |(x1, y1), (x2, y2)| (x1 + x2, y1 + y2);

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();
    for line in stdin {
        let line = line.unwrap();
        for c in line.chars() {
            p1 = part1_next(p1, c);
            let new_cur = step(p2_cur, translate_move(c));
            if keypad.contains_key(&new_cur) {
                p2_cur = new_cur;
            }
        }
        part1.push(char::from_digit(p1, 10).unwrap());
        part2.push(*keypad.get(&p2_cur).unwrap());
    }

    println!("part1: {}", part1);
    println!("part2: {}", part2);
}
<commit_msg>use more idiomatic rust<commit_after>use std::io;
use std::io::prelude::*;
use std::char;
use std::collections::HashMap;

fn part1_next(n: u32, d: char) -> u32 {
    match d {
        'U' if n > 3 => n - 3,
        'D' if n < 7 => n + 3,
        'L' if n % 3 != 1 => n - 1,
        'R' if n % 3 != 0 => n + 1,
        _ => n,
    }
}

#[cfg_attr(rustfmt, rustfmt_skip)]
const P2_KEYPAD: &'static [((i8, i8), char)] = &[
                            ((2,4), '1'),
              ((1,3), '2'), ((2,3), '3'), ((3,3), '4'),
((0,2), '5'), ((1,2), '6'), ((2,2), '7'), ((3,2), '8'), ((4,2), '9'),
              ((1,1), 'A'), ((2,1), 'B'), ((3,1), 'C'),
                            ((2,0), 'D')
];

#[cfg_attr(rustfmt, rustfmt_skip)]
fn translate_move(d: char) -> (i8, i8) {

    match d {
        'U' => ( 0,  1),
        'D' => ( 0, -1),
        'R' => ( 1,  0),
        'L' => (-1,  0),
        _ => panic!("invalid input"),
    }
}

fn main() {
    let mut part1 = String::new();
    let mut part2 = String::new();
    let mut p1 = 5;
    let mut p2_cur = (0, 2); // start at the coordinate of '5'

    let keypad: HashMap<(i8, i8), char> = P2_KEYPAD.iter().cloned().collect();
    let step = |(x1, y1), (x2, y2)| (x1 + x2, y1 + y2);

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();
    for line in stdin {
        let line = line.unwrap();
        for c in line.chars() {
            p1 = part1_next(p1, c);
            let new_cur = step(p2_cur, translate_move(c));
            if keypad.contains_key(&new_cur) {
                p2_cur = new_cur;
            }
        }
        part1.push(char::from_digit(p1, 10).unwrap());
        part2.push(keypad[&p2_cur]);
    }

    println!("part1: {}", part1);
    println!("part2: {}", part2);
}
<|endoftext|>


<commit_before>extern crate uuid;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use self::uuid::Uuid;
use super::super::math::vector3::Vector3;
use super::super::math::quaternion::Quaternion;
use super::super::math::matrix4::Matrix4;
use super::super::math::matrix3::Matrix3;
use super::super::math::euler::Euler;
use super::layers::Layers;

pub static mut DEFAULT_UP: Vector3 = Vector3 {
	x: 0.0,
	y: 1.0,
	z: 0.0,
};
pub static mut DEFAULT_MATRIX_AUTO_UPDATE: bool = true;

#[derive(Debug, Clone)]
pub struct Object3D {
	uuid: Uuid,
	name: &'static str,
	children: Vec<Rc<RefCell<Object3D>>>,
	up: Vector3,
	position: Vector3,
	quaternion: Quaternion,
	scale: Vector3,
	matrix_auto_update: bool,
	matrix_world_needs_update: bool,
	model_view_matrix: Matrix4,
	normal_matrix: Matrix3,
	matrix: Matrix4,
	matrix_world: Matrix4,
	layers: Layers,
	visible: bool,
	cast_shadow: bool,
	receive_shadow: bool,
	frustum_culled: bool,
	render_order: u32
}

impl Object3D {
	pub fn new() -> Object3D {
		Object3D {
			uuid: Uuid::new_v4(),
			name: "",
			children: vec![],
			up: unsafe {DEFAULT_UP},
			position: Vector3::new(),
			quaternion: Quaternion::new(),
			scale: Vector3 {
				x: 1.0,
				y: 1.0,
				z: 1.0,
			},
			model_view_matrix: Matrix4::new(),
			normal_matrix: Matrix3::new(),
			matrix: Matrix4::new(),
			matrix_world: Matrix4::new(),
			matrix_auto_update: unsafe {DEFAULT_MATRIX_AUTO_UPDATE},
			matrix_world_needs_update: false,
			layers: Layers::new(),
			visible: true,
			cast_shadow: false,
			receive_shadow: false,
			frustum_culled: true,
			render_order: 0,
		}
	}

	pub fn apply_matrix(&mut self, matrix: &Matrix4) {
		let m = self.matrix;
		self.matrix.multiply_matrices(matrix, &m);
		let mut p = self.position;
		let mut q = self.quaternion;
		let mut s = self.scale;
		self.matrix.decompose(&mut p, &mut q, &mut s);
		self.position = p;
		self.quaternion = q;
		self.scale = s;
	}

	pub fn set_rotation_from_axis_angle(&mut self, axis: &Vector3, angle: f32) {
		self.quaternion.set_from_axis_angle(axis, angle);
	}

	pub fn set_rotation_from_euler(&mut self, euler: &Euler) {
		self.quaternion.set_from_euler(euler);
	}

	pub fn set_rotation_from_matrix(&mut self, m: &Matrix4) {
		self.quaternion.set_from_rotation_matrix(m);
	}

	pub fn set_rotation_from_quaternion(&mut self, q: &Quaternion) {
		self.quaternion.copy(q);
	}

	pub fn rotate_on_axis(&mut self, axis: &Vector3, angle: f32) {
		let mut q1 = Quaternion::new();
		q1.set_from_axis_angle(axis, angle);
		self.quaternion.multiply(&q1);
	}

	pub fn rotate_x(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 1.0,
			y: 0.0,
			z: 0.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn rotate_y(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 1.0,
			z: 0.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn rotate_z(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 0.0,
			z: 1.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn translate_on_axis(&mut self, axis: &Vector3, distance: f32) {
		let mut v1 = Vector3::new();
		v1.copy(axis);
		v1.apply_quaternion(&self.quaternion);
		v1.multiply_scalar(distance);
		self.position.add(&v1);
	}

	pub fn translate_x(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 1.0,
			y: 0.0,
			z: 0.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn translate_y(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 1.0,
			z: 0.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn translate_z(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 0.0,
			z: 1.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn local_to_world(&self, vector: &mut Vector3) {
		vector.apply_matrix4(&self.matrix_world);
	}

	pub fn world_to_local(&self, vector: &mut Vector3) {
		let mut m1 = Matrix4::new();
		m1.get_inverse(&self.matrix_world, false);
		vector.apply_matrix4(&m1);
	}

	pub fn look_at(&mut self, vector: &Vector3) {
		let mut m1 = Matrix4::new();
		m1.look_at(vector, &self.position, &self.up);
		self.quaternion.set_from_rotation_matrix(&m1);
	}

	// pub fn add(&mut self, )
}<commit_msg>object3d add with parent<commit_after>extern crate uuid;
use std::rc::{Rc, Weak};
use std::cell::{Ref, RefMut, RefCell};
use std::cmp::{Eq, PartialEq};
use self::uuid::Uuid;
use super::super::math::vector3::Vector3;
use super::super::math::quaternion::Quaternion;
use super::super::math::matrix4::Matrix4;
use super::super::math::matrix3::Matrix3;
use super::super::math::euler::Euler;
use super::layers::Layers;

pub static mut DEFAULT_UP: Vector3 = Vector3 {
	x: 0.0,
	y: 1.0,
	z: 0.0,
};
pub static mut DEFAULT_MATRIX_AUTO_UPDATE: bool = true;

#[derive(Debug, Clone)]
pub struct Object3D {
	_self: Option<Weak<RefCell<Object3D>>>,
	uuid: Uuid,
	name: &'static str,
	children: Vec<Rc<RefCell<Object3D>>>,
	up: Vector3,
	position: Vector3,
	quaternion: Quaternion,
	scale: Vector3,
	matrix_auto_update: bool,
	matrix_world_needs_update: bool,
	model_view_matrix: Matrix4,
	normal_matrix: Matrix3,
	matrix: Matrix4,
	matrix_world: Matrix4,
	layers: Layers,
	visible: bool,
	cast_shadow: bool,
	receive_shadow: bool,
	frustum_culled: bool,
	render_order: u32,
	parent: Option<Rc<RefCell<Object3D>>>,
}

impl PartialEq for Object3D {
	 fn eq(&self, other: &Object3D) -> bool {
		 self.uuid == other.uuid
	 }
}

impl Object3D {
	pub fn new() -> Rc<RefCell<Object3D>> {
		let mut o = Object3D {
			_self: Option::None,
			uuid: Uuid::new_v4(),
			name: "",
			children: vec![],
			up: unsafe {DEFAULT_UP},
			position: Vector3::new(),
			quaternion: Quaternion::new(),
			scale: Vector3 {
				x: 1.0,
				y: 1.0,
				z: 1.0,
			},
			model_view_matrix: Matrix4::new(),
			normal_matrix: Matrix3::new(),
			matrix: Matrix4::new(),
			matrix_world: Matrix4::new(),
			matrix_auto_update: unsafe {DEFAULT_MATRIX_AUTO_UPDATE},
			matrix_world_needs_update: false,
			layers: Layers::new(),
			visible: true,
			cast_shadow: false,
			receive_shadow: false,
			frustum_culled: true,
			render_order: 0,
			parent: Option::None,
		};
		let rc = Rc::new(RefCell::from(o));
		let weak = Rc::downgrade(&rc);
		rc.borrow_mut()._self = Some(weak);
		rc
	}

	pub fn apply_matrix(&mut self, matrix: &Matrix4) {
		let m = self.matrix;
		self.matrix.multiply_matrices(matrix, &m);
		let mut p = self.position;
		let mut q = self.quaternion;
		let mut s = self.scale;
		self.matrix.decompose(&mut p, &mut q, &mut s);
		self.position = p;
		self.quaternion = q;
		self.scale = s;
	}

	pub fn set_rotation_from_axis_angle(&mut self, axis: &Vector3, angle: f32) {
		self.quaternion.set_from_axis_angle(axis, angle);
	}

	pub fn set_rotation_from_euler(&mut self, euler: &Euler) {
		self.quaternion.set_from_euler(euler);
	}

	pub fn set_rotation_from_matrix(&mut self, m: &Matrix4) {
		self.quaternion.set_from_rotation_matrix(m);
	}

	pub fn set_rotation_from_quaternion(&mut self, q: &Quaternion) {
		self.quaternion.copy(q);
	}

	pub fn rotate_on_axis(&mut self, axis: &Vector3, angle: f32) {
		let mut q1 = Quaternion::new();
		q1.set_from_axis_angle(axis, angle);
		self.quaternion.multiply(&q1);
	}

	pub fn rotate_x(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 1.0,
			y: 0.0,
			z: 0.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn rotate_y(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 1.0,
			z: 0.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn rotate_z(&mut self, angle: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 0.0,
			z: 1.0,
		};
		self.rotate_on_axis(&v1, angle);
	}

	pub fn translate_on_axis(&mut self, axis: &Vector3, distance: f32) {
		let mut v1 = Vector3::new();
		v1.copy(axis);
		v1.apply_quaternion(&self.quaternion);
		v1.multiply_scalar(distance);
		self.position.add(&v1);
	}

	pub fn translate_x(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 1.0,
			y: 0.0,
			z: 0.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn translate_y(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 1.0,
			z: 0.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn translate_z(&mut self, distance: f32) {
		let v1 = Vector3 {
			x: 0.0,
			y: 0.0,
			z: 1.0,
		};
		self.translate_on_axis(&v1, distance);
	}

	pub fn local_to_world(&self, vector: &mut Vector3) {
		vector.apply_matrix4(&self.matrix_world);
	}

	pub fn world_to_local(&self, vector: &mut Vector3) {
		let mut m1 = Matrix4::new();
		m1.get_inverse(&self.matrix_world, false);
		vector.apply_matrix4(&m1);
	}

	pub fn look_at(&mut self, vector: &Vector3) {
		let mut m1 = Matrix4::new();
		m1.look_at(vector, &self.position, &self.up);
		self.quaternion.set_from_rotation_matrix(&m1);
	}

	pub fn add(&mut self, object: Rc<RefCell<Object3D>>) {
		let ref mut s = self._self;
		let self_rc = s.as_mut().unwrap().upgrade().unwrap();
		object.borrow_mut().parent = Some(self_rc);
		self.children.push(object);
	}
}<|endoftext|>