<commit_before>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = mut_addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz unsafe {
    let res = init();
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    assert(res.set_str(other.to_str(), 10));
    res
  }
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    init_set_str(s, 10)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, 10, addr_of(&self.mpz)))
  }
}

pub fn init() -> Mpz {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

pub fn init_set_str(s: &str, base: int) -> Option<Mpz> {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }

  #[test]
  fn eq() {
    let x = init();
    x.set_str("4242142195", 10);
    let y = init();
    y.set_str("4242142195", 10);
    let z = init();
    z.set_str("4242142196", 10);

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = init();
    x.set_str("40000000000000000000000", 10);
    let y = init();
    y.set_str("45000000000000000000000", 10);
    let z = init();
    z.set_str("50000000000000000000000", 10);

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x = init();
    let y = init();
    let mut z: Mpz;

    x.set_str("2", 10);
    y.set_str("3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / 3) == 0);

    x.set_str("2", 10);
    y.set_str("-3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / -3) == 0);
  }

  #[test]
  fn to_str() {
    let x = init();
    x.set_str("1234567890", 10);
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(init_set_str("foobar", 10).is_none());
  }
}
<commit_msg>use init_set_str in tests<commit_after>extern mod std;

use libc::c_char;
use libc::c_int;
use libc::size_t;
use libc::c_ulong;
use libc::c_void;
use ptr::null;
use ptr::addr_of;
use ptr::mut_addr_of;
use str::as_c_str;

struct mpz_struct {
  _mp_alloc: c_int,
  _mp_size: c_int,
  _mp_d: *c_void
}

type mpz_srcptr = *const mpz_struct;
type mpz_ptr = *mut mpz_struct;

extern mod gmp {
  fn __gmpz_init(x: mpz_ptr);
  fn __gmpz_init_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_clear(x: mpz_ptr);
  fn __gmpz_set_str(rop: mpz_ptr, str: *c_char, base: c_int) -> c_int;
  fn __gmpz_get_str(str: *c_char, base: c_int, op: mpz_srcptr) -> *c_char;
  pure fn __gmpz_sizeinbase(op: mpz_srcptr, base: c_int) -> size_t;
  pure fn __gmpz_cmp(op: mpz_srcptr, op2: mpz_srcptr) -> c_int;
  pure fn __gmpz_cmp_ui(op1: mpz_srcptr, op2: c_ulong) -> c_int;
  fn __gmpz_add(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_sub(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_mul(rop: mpz_ptr, op1: mpz_srcptr, op2: mpz_srcptr);
  fn __gmpz_neg(rop: mpz_ptr, op: mpz_srcptr);
  fn __gmpz_tdiv_q(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
  fn __gmpz_mod(r: mpz_ptr, n: mpz_srcptr, d: mpz_srcptr);
}

use gmp::*;

pub struct Mpz {
  priv mpz: mpz_struct,

  drop {
    __gmpz_clear(mut_addr_of(&self.mpz));
  }
}

impl Mpz {
  fn set_str(&self, s: &str, base: int) -> bool {
    let mpz = mut_addr_of(&self.mpz);
    let r = as_c_str(s, { |s| __gmpz_set_str(mpz, s, base as c_int) });
    r == 0
  }

  pure fn size_in_base(&self, base: int) -> uint {
    __gmpz_sizeinbase(addr_of(&self.mpz), base as c_int) as uint
  }
}

impl Mpz: cmp::Eq {
  pure fn eq(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) == 0
  }
  pure fn ne(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) != 0
  }
}

impl Mpz: cmp::Ord {
  pure fn lt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) < 0
  }
  pure fn le(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) <= 0
  }
  pure fn gt(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) > 0
  }
  pure fn ge(other: &Mpz) -> bool {
    __gmpz_cmp(addr_of(&self.mpz), addr_of(&other.mpz)) >= 0
  }
}

impl Mpz: num::Num {
  pure fn add(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_add(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn sub(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_sub(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn mul(other: &Mpz) -> Mpz unsafe {
    let res = init();
    __gmpz_mul(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn div(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_tdiv_q(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn modulo(other: &Mpz) -> Mpz unsafe {
    if __gmpz_cmp_ui(addr_of(&self.mpz), 0) == 0 {
      fail ~"divide by zero";
    }

    let res = init();
    __gmpz_mod(mut_addr_of(&res.mpz), addr_of(&self.mpz), addr_of(&other.mpz));
    res
  }
  pure fn neg() -> Mpz unsafe {
    let res = init();
    __gmpz_neg(mut_addr_of(&res.mpz), addr_of(&self.mpz));
    res
  }
  pure fn to_int() -> int {
    fail ~"not implemented";
  }
  static pure fn from_int(other: int) -> Mpz unsafe {
    let res = init();
    // the gmp functions dealing with longs aren't usable here - long is only
    // guaranteed to be at least 32-bit
    assert(res.set_str(other.to_str(), 10));
    res
  }
}

impl Mpz : from_str::FromStr {
  static fn from_str(s: &str) -> Option<Mpz> {
    init_set_str(s, 10)
  }
}

impl Mpz : to_str::ToStr {
  pure fn to_str() -> ~str unsafe {
    let length = self.size_in_base(10) + 2;
    let dst = vec::to_mut(vec::from_elem(length, '0'));
    let pdst = vec::raw::to_ptr(dst);

    str::raw::from_c_str(__gmpz_get_str(pdst as *c_char, 10, addr_of(&self.mpz)))
  }
}

pub fn init() -> Mpz {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  __gmpz_init(mut_addr_of(&mpz));
  Mpz { mpz: mpz }
}

pub fn init_set_str(s: &str, base: int) -> Option<Mpz> {
  let mpz = mpz_struct { _mp_alloc: 0, _mp_size: 0, _mp_d: null() };
  let mpz_ptr = mut_addr_of(&mpz);
  let r = as_c_str(s, { |s| __gmpz_init_set_str(mpz_ptr, s, base as c_int) });
  if r == 0 {
    Some(Mpz { mpz: mpz })
  } else {
    __gmpz_clear(mpz_ptr);
    None
  }
}

#[cfg(test)]
mod tests {
  #[test]
  fn size_in_base() {
    let x = init();
    x.set_str("150000", 10);
    assert(x.size_in_base(10) == 6);
  }

  #[test]
  fn eq() {
    let x = option::unwrap(init_set_str("4242142195", 10));
    let y = option::unwrap(init_set_str("4242142195", 10));
    let z = option::unwrap(init_set_str("4242142196", 10));

    assert(x == y);
    assert(x != z);
    assert(y != z);
  }

  #[test]
  fn ord() {
    let x = option::unwrap(init_set_str("40000000000000000000000", 10));
    let y = option::unwrap(init_set_str("45000000000000000000000", 10));
    let z = option::unwrap(init_set_str("50000000000000000000000", 10));

    assert(x < y && x < z && y < z);
    assert(x <= x && x <= y && x <= z && y <= z);
    assert(z > y && z > x && y > x);
    assert(z >= z && z >= y && z >= x && y >= x);
  }

  #[test]
  #[should_fail]
  fn div_zero() {
    let x = init();
    x / x;
  }

  #[test]
  #[should_fail]
  fn modulo_zero() {
    let x = init();
    x % x;
  }

  #[test]
  fn test_div_round() {
    let x = init();
    let y = init();
    let mut z: Mpz;

    x.set_str("2", 10);
    y.set_str("3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / 3) == 0);

    x.set_str("2", 10);
    y.set_str("-3", 10);
    z = x / y;
    assert(__gmpz_cmp_ui(addr_of(&z.mpz), 2 / -3) == 0);
  }

  #[test]
  fn to_str() {
    let x = option::unwrap(init_set_str("1234567890", 10));
    assert(x.to_str() == ~"1234567890");
  }

  #[test]
  fn invalid_str() {
    assert(init_set_str("foobar", 10).is_none());
  }
}
<|endoftext|>


<commit_before>// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency
use sdl::*;
use start;

#[test]
pub fn test_everything() {
    do start::start {
        start_tests();
    }
}

fn start_tests() {
    assert init(~[InitVideo, InitTimer]) == true;
    run_tests(~[
        general::test_was_init,
        // FIXME: Busted, segfault
        //general::test_set_error,
        //general::test_error,
        //general::test_clear_error,
        test_video::test_set_video_mode,
        // FIXME: Doesn't work when called from a directory that
        // doesn't contain the test image file
        //test_video::test_blit,
        test_event::test_poll_event_none,
        // FIXME: This test is interactive
        //test_event::test_keyboard,

    ]);

    quit();
}

fn run_tests(tests: &[extern fn()]) {
    for tests.each |test| {
        (*test)();
    }
}

mod general {

    use sdl::*;

    pub fn test_was_init() {
        assert vec::contains(~[InitTimer], &InitTimer);
    }

    pub fn test_set_error() {
        set_error(~"test");
        assert get_error() == ~"test";
    }

    pub fn test_error() {
        clear_error();
        assert str::is_empty(get_error());
        error(ENoMem);
        assert (str::is_empty(get_error()) == false);
    }

    pub fn test_clear_error() {
        set_error(~"test");
        clear_error();
        assert str::is_empty(get_error());
    }
}

mod test_event {

    use event;
    use video;
    use keyboard;

    pub fn test_poll_event_none() {
        assert event::poll_event() == event::NoEvent;
    }

    pub fn test_keyboard() {
        io::println(~"press a key in the window");
        let maybe_surface = video::set_video_mode(320, 200, 32,
            ~[video::SWSurface], ~[video::DoubleBuf, video::Resizable]);

        match maybe_surface {
            result::Ok(_) => {
                let mut keydown = false;
                let mut keyup = false;
                while !keydown || !keyup {
                    match event::poll_event() {
                      event::KeyUpEvent(keyboard) => {
                          keyup = true;
                          assert keyboard.keycode != keyboard::SDLKUnknown;
                      },
                      event::KeyDownEvent(keyboard) => {
                          keydown = true;
                          assert keyboard.keycode != keyboard::SDLKUnknown;
                      },
                      event::QuitEvent => fail!(~"Explicit quit"),
                      _ => { }
                    }
                }
            }
            result::Err(_) => {
                fail!(~"Failed to set video mode");
            }
        }
    }
}

mod test_video {

    pub fn test_set_video_mode() {
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::HWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_surface);
    }

    pub fn test_blit() {
        let maybe_screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_screen);

        match maybe_screen {
            result::Ok(screen) => {
                // FIXME: We need to load this from the crate instead of
                // off the filesystem
                let maybe_image = match ::video::load_bmp(~"rust-logo-128x128-blk.bmp") {
                    result::Ok(raw_image) => {
                        raw_image.display_format()
                    },
                    result::Err(err) => result::Err(err)
                };

                assert result::is_ok(&maybe_image);

                match maybe_image {
                    result::Ok(image) => {
                        for iter::repeat(1u) || {
                            screen.blit_surface(image);
                            screen.flip();
                            ::event::poll_event();
                        };
                    },
                    result::Err(_) => ()
                };
            },
            result::Err(_) => ()
        };
    }
}
<commit_msg>Added unit test for with_lock<commit_after>// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency
use sdl::*;
use start;

#[test]
pub fn test_everything() {
    do start::start {
        start_tests();
    }
}

fn start_tests() {
    assert init(~[InitVideo, InitTimer]) == true;
    run_tests(~[
        general::test_was_init,
        // FIXME: Busted, segfault
        //general::test_set_error,
        //general::test_error,
        //general::test_clear_error,
        test_video::test_set_video_mode,
        test_video::test_with_lock,
        // FIXME: Doesn't work when called from a directory that
        // doesn't contain the test image file
        //test_video::test_blit,
        test_event::test_poll_event_none,
        // FIXME: This test is interactive
        //test_event::test_keyboard,

    ]);

    quit();
}

fn run_tests(tests: &[extern fn()]) {
    for tests.each |test| {
        (*test)();
    }
}

mod general {

    use sdl::*;

    pub fn test_was_init() {
        assert vec::contains(~[InitTimer], &InitTimer);
    }

    pub fn test_set_error() {
        set_error(~"test");
        assert get_error() == ~"test";
    }

    pub fn test_error() {
        clear_error();
        assert str::is_empty(get_error());
        error(ENoMem);
        assert (str::is_empty(get_error()) == false);
    }

    pub fn test_clear_error() {
        set_error(~"test");
        clear_error();
        assert str::is_empty(get_error());
    }
}

mod test_event {

    use event;
    use video;
    use keyboard;

    pub fn test_poll_event_none() {
        assert event::poll_event() == event::NoEvent;
    }

    pub fn test_keyboard() {
        io::println(~"press a key in the window");
        let maybe_surface = video::set_video_mode(320, 200, 32,
            ~[video::SWSurface], ~[video::DoubleBuf, video::Resizable]);

        match maybe_surface {
            result::Ok(_) => {
                let mut keydown = false;
                let mut keyup = false;
                while !keydown || !keyup {
                    match event::poll_event() {
                      event::KeyUpEvent(keyboard) => {
                          keyup = true;
                          assert keyboard.keycode != keyboard::SDLKUnknown;
                      },
                      event::KeyDownEvent(keyboard) => {
                          keydown = true;
                          assert keyboard.keycode != keyboard::SDLKUnknown;
                      },
                      event::QuitEvent => fail!(~"Explicit quit"),
                      _ => { }
                    }
                }
            }
            result::Err(_) => {
                fail!(~"Failed to set video mode");
            }
        }
    }
}

mod test_video {

    pub fn test_set_video_mode() {
        let maybe_surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::HWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_surface);
    }

    pub fn test_blit() {
        let maybe_screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_screen);

        match maybe_screen {
            result::Ok(screen) => {
                // FIXME: We need to load this from the crate instead of
                // off the filesystem
                let maybe_image = match ::video::load_bmp(~"rust-logo-128x128-blk.bmp") {
                    result::Ok(raw_image) => {
                        raw_image.display_format()
                    },
                    result::Err(err) => result::Err(err)
                };

                assert result::is_ok(&maybe_image);

                match maybe_image {
                    result::Ok(image) => {
                        for iter::repeat(1u) || {
                            screen.blit_surface(image);
                            screen.flip();
                            ::event::poll_event();
                        };
                    },
                    result::Err(_) => ()
                };
            },
            result::Err(_) => ()
        };
    }

    pub fn test_with_lock() {
        let maybe_screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::SWSurface], ~[::video::DoubleBuf]);

        assert result::is_ok(&maybe_screen);

        match maybe_screen {
            result::Ok(screen) => {
                //Set all the pixels to green
                do screen.with_lock |raw| {
                    for uint::range(0, raw.len() / 4) |idx| {
                        let true_idx = idx * 4;
                        raw[true_idx] = 0;
                        raw[true_idx + 1] = 0xFF;
                        raw[true_idx + 2] = 0;
                        raw[true_idx + 3] = 0xFF;
                    }
                }
                //Then check that it makes sense
                do screen.with_lock |raw| {
                    //Check the 23rd pixel
                    let start = 23 * 4;
                    assert raw[start] == 0;
                    assert raw[start + 1] == 0xFF;
                    assert raw[start + 2] == 0;
                    assert raw[start + 3] == 0xFF;
                }
            },
            result::Err(message) => fail!(message)
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>Invalid source code formatting Fixed<commit_after><|endoftext|>


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

// This test case tests the incremental compilation hash (ICH) implementation
// for closure expression.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Change closure body ---------------------------------------------------------
#[cfg(cfail1)]
fn change_closure_body() {
    let _ = || 1u32;
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_closure_body() {
    let _ = || 3u32;
}

// Add parameter ---------------------------------------------------------------
#[cfg(cfail1)]
fn add_parameter() {
    let x = 0u32;
    let _ = || x + 1;
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_parameter() {
    let x = 0u32;
    let _ = |x: u32| x + 1;
}

// Change parameter pattern ----------------------------------------------------
#[cfg(cfail1)]
fn change_parameter_pattern() {
    let _ = |x: &u32| x;
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_parameter_pattern() {
    let _ = |&x: &u32| x;
}

// Add `move` to closure -------------------------------------------------------
#[cfg(cfail1)]
fn add_move() {
    let _ = || 1;
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_move() {
    let _ = move || 1;
}

// Add type ascription to parameter --------------------------------------------
#[cfg(cfail1)]
fn add_type_ascription_to_parameter() {
    let closure = |x| x + 1u32;
    let _: u32 = closure(1);
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_type_ascription_to_parameter() {
    let closure = |x: u32| x + 1u32;
    let _: u32 = closure(1);
}

// Change parameter type -------------------------------------------------------
#[cfg(cfail1)]
fn change_parameter_type() {
    let closure = |x: u32| (x as u64) + 1;
    let _ = closure(1);
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_parameter_type() {
    let closure = |x: u16| (x as u64) + 1;
    let _ = closure(1);
}
<|endoftext|>


<commit_before><commit_msg>getting travis to work<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for escaping LLVMisms in inline asm<commit_after>// FIXME(nagisa): remove the flags here once all targets support `asm!`.
// compile-flags: --target x86_64-unknown-linux-gnu

// Verify we sanitize the special tokens for the LLVM inline-assembly, ensuring people won't
// inadvertently rely on the LLVM-specific syntax and features.
#![no_core]
#![feature(no_core, lang_items, rustc_attrs)]
#![crate_type = "rlib"]

#[rustc_builtin_macro]
macro_rules! asm {
    () => {};
}

#[lang = "sized"]
trait Sized {}
#[lang = "copy"]
trait Copy {}

pub unsafe fn we_escape_dollar_signs() {
    // CHECK: call void asm sideeffect alignstack inteldialect "banana$$:"
    asm!(
        r"banana$:",
    )
}

pub unsafe fn we_escape_escapes_too() {
    // CHECK: call void asm sideeffect alignstack inteldialect "banana\{{(\\|5C)}}36:"
    asm!(
        r"banana\36:",
    )
}
<|endoftext|>


<commit_before><commit_msg>Check const-propagation of borrows of unsized places<commit_after>// run-pass (ensure that const-prop is run)

struct A<T: ?Sized>(T);

fn main() {
    let _x = &(&A([2, 3]) as &A<[i32]>).0 as *const [i32] as *const i32;
}
<|endoftext|>


<commit_before><commit_msg>Impl square for 3.1<commit_after><|endoftext|>


<commit_before><commit_msg>adds example of capturing an image<commit_after>extern crate gphoto;

use std::path::Path;

fn main() {
    let mut context = match gphoto::Context::new() {
        Ok(c) => c,
        Err(err) => panic!("error creating context: {}", err)
    };

    // open camera

    println!("opening camera ...");
    let mut camera = match gphoto::Camera::autodetect(&mut context) {
        Ok(c) => c,
        Err(err) => panic!("error opening camera: {}", err)
    };
    println!(" (done)");

    // capture image

    println!("capturing image ...");
    let capture = match camera.capture_image(&mut context) {
        Ok(c) => c,
        Err(err) => panic!("error capturing image: {}", err)
    };
    println!(" (done) {:?}", capture.basename());

    // download file

    let mut file = match gphoto::FileMedia::create(Path::new(capture.basename().as_ref())) {
        Ok(f) => f,
        Err(err) => panic!("error saving file: {}", err)
    };

    println!("downloading ...");
    if let Err(err) = camera.download(&mut context, &capture, &mut file) {
        panic!("error downloading file: {}", err);
    }
    println!(" (done)");
}
<|endoftext|>


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

#![deny(warnings)]

#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]
struct Foo;

fn main() {
    let _ = Foo;
}<|endoftext|>


<commit_before><commit_msg>testcase added for #3878<commit_after>// Issue #3878
// Issue Name: Unused move causes a crash
// Abstract: zero-fill to block after drop

fn main()
{
    let y = ~1;
    move y;
}<|endoftext|>


<commit_before><commit_msg>Use generate_runtime_setup() to create Runtime object<commit_after><|endoftext|>


<commit_before><commit_msg>modules<commit_after>mod game1 {
    fn func1(){
        println!("我是不是可见的?");
    }

    pub fn func2(){
        println!("func2调用");
    }
}

fn main() {
    //game1::func1(); //错误
    game1::func2();
}<|endoftext|>


<commit_before><commit_msg>feat: Simple benchmark example<commit_after>extern crate rustc_serialize;
extern crate redis;
extern crate oppgave;
extern crate libc;

use oppgave::Queue;
use std::str::FromStr;
use std::process::Command;
use std::time::{Duration, Instant};
use std::{thread, process};

#[derive(RustcDecodable, RustcEncodable, Debug)]
struct Job {
    id: usize
}

impl Job {
    pub fn process(&self) {
        // This is left empty
    }
}

fn load(n: usize) {
    let client = redis::Client::open("redis://127.0.0.1/").unwrap();
    let con = client.get_connection().unwrap();
    let q = Queue::new("default".into(), con);

    let now = Instant::now();
    for i in 0..n {
        let j = Job{ id: i };
        q.push(j).unwrap();
    }

    println!("Created {} tasks in {} seconds", n, now.elapsed().as_secs());
}

fn process_rss(pid: i32) -> u64 {
    let output = Command::new("ps")
        .arg("-o")
        .arg("rss=")
        .arg("-p")
        .arg(format!("{}", pid))
        .output()
        .unwrap_or_else(|e| { panic!("failed to execute process: {}", e)  });

    let s = String::from_utf8_lossy(&output.stdout);
    let end = s.find('\n').unwrap();
    FromStr::from_str(&s[1..end]).unwrap()
}

fn main() {
    let total = 10 * 10_000;
    load(total);

    thread::spawn(move || {
        let pid = unsafe { libc::getpid() };
        let queue_name = "oppgave:default";
        let client = redis::Client::open("redis://127.0.0.1/").unwrap();
        let con = client.get_connection().unwrap();

        let now = Instant::now();

        loop {
            let count : u64 = redis::cmd("LLEN").arg(queue_name).query(&con).unwrap();
            if count == 0 {
                let elapsed = now.elapsed().as_secs();
                let per_second = total as f64 / elapsed as f64;
                println!("Done in {}: {} jobs/sec", elapsed, per_second);
                process::exit(0);
            }

            println!("pid: {}, count: {}, rss: {}", pid, count, process_rss(pid));
            thread::sleep(Duration::from_millis(200));
        }
    });

    let client = redis::Client::open("redis://127.0.0.1/").unwrap();
    let con = client.get_connection().unwrap();
    let worker = Queue::new("default".into(), con);

    while let Some(task) = worker.next::<Job>() {
        if task.is_err() { continue; }
        let task = task.unwrap();
        task.process();
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #61 - Ogeon:tiny_hello, r=Ogeon<commit_after>#[macro_use]
extern crate rustful;
use std::error::Error;
use rustful::{Server, Context, Response};

fn main() {
    println!("Visit http://localhost:8080 to try this example.");
    let server_result = Server {
        host: 8080.into(),
        ..Server::new(|_: Context, res: Response| res.send("Hello!"))
    }.run();

    match server_result {
        Ok(_server) => {},
        Err(e) => println!("could not start server: {}", e.description())
    }
}<|endoftext|>


<commit_before><commit_msg>Auto merge of #61 - Ogeon:tiny_hello, r=Ogeon<commit_after><|endoftext|>


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

// Information concerning the machine representation of various types.

use middle::trans::common::*;
use middle::trans::type_of;
use middle::ty::field;
use middle::ty;

use syntax::parse::token::special_idents;

// Creates a simpler, size-equivalent type. The resulting type is guaranteed
// to have (a) the same size as the type that was passed in; (b) to be non-
// recursive. This is done by replacing all boxes in a type with boxed unit
// types.
// This should reduce all pointers to some simple pointer type, to
// ensure that we don't recurse endlessly when computing the size of a
// nominal type that has pointers to itself in it.
pub fn simplify_type(tcx: ty::ctxt, typ: ty::t) -> ty::t {
    fn nilptr(tcx: ty::ctxt) -> ty::t {
        ty::mk_ptr(tcx, ty::mt {ty: ty::mk_nil(tcx), mutbl: ast::m_imm})
    }
    fn simplifier(tcx: ty::ctxt, typ: ty::t) -> ty::t {
        match ty::get(typ).sty {
          ty::ty_box(_) | ty::ty_opaque_box | ty::ty_uniq(_) |
          ty::ty_evec(_, ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_box) |
          ty::ty_estr(ty::vstore_uniq) | ty::ty_estr(ty::vstore_box) |
          ty::ty_ptr(_) | ty::ty_rptr(*) => nilptr(tcx),

          ty::ty_bare_fn(*) | // FIXME(#4804) Bare fn repr
          ty::ty_closure(*) => ty::mk_tup(tcx, ~[nilptr(tcx), nilptr(tcx)]),

          ty::ty_evec(_, ty::vstore_slice(_)) |
          ty::ty_estr(ty::vstore_slice(_)) => {
            ty::mk_tup(tcx, ~[nilptr(tcx), ty::mk_int(tcx)])
          }
          // Reduce a class type to a record type in which all the fields are
          // simplified
          ty::ty_struct(did, ref substs) => {
            let simpl_fields = (if ty::ty_dtor(tcx, did).is_present() {
                // remember the drop flag
                  ~[field {
                    ident: special_idents::dtor,
                    mt: ty::mt {ty: ty::mk_u8(tcx), mutbl: ast::m_mutbl}
                   }] }
                else { ~[] }) +
                do ty::lookup_struct_fields(tcx, did).map |f| {
                 let t = ty::lookup_field_type(tcx, did, f.id, substs);
                 field {
                    ident: f.ident,
                    mt: ty::mt {ty: simplify_type(tcx, t), mutbl: ast::m_const
                 }}
            };
            ty::mk_rec(tcx, simpl_fields)
          }
          _ => typ
        }
    }
    ty::fold_ty(tcx, typ, |t| simplifier(tcx, t))
}

// ______________________________________________________________________
// compute sizeof / alignof

pub type metrics = {
    bcx: block,
    sz: ValueRef,
    align: ValueRef
};

pub type tag_metrics = {
    bcx: block,
    sz: ValueRef,
    align: ValueRef,
    payload_align: ValueRef
};

// Returns the number of bytes clobbered by a Store to this type.
pub fn llsize_of_store(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMStoreSizeOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the number of bytes between successive elements of type T in an
// array of T. This is the "ABI" size. It includes any ABI-mandated padding.
pub fn llsize_of_alloc(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMABISizeOfType(cx.td.lltd, t) as uint;
    }
}

// Returns, as near as we can figure, the "real" size of a type. As in, the
// bits in this number of bytes actually carry data related to the datum
// with the type. Not junk, padding, accidentally-damaged words, or
// whatever. Rounds up to the nearest byte though, so if you have a 1-bit
// value, we return 1 here, not 0. Most of rustc works in bytes. Be warned
// that LLVM *does* distinguish between e.g. a 1-bit value and an 8-bit value
// at the codegen level! In general you should prefer `llbitsize_of_real`
// below.
pub fn llsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        let nbits = llvm::LLVMSizeOfTypeInBits(cx.td.lltd, t) as uint;
        if nbits & 7u != 0u {
            // Not an even number of bytes, spills into "next" byte.
            1u + (nbits >> 3)
        } else {
            nbits >> 3
        }
    }
}

/// Returns the "real" size of the type in bits.
pub fn llbitsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        llvm::LLVMSizeOfTypeInBits(cx.td.lltd, t) as uint
    }
}

// Returns the "default" size of t, which is calculated by casting null to a
// *T and then doing gep(1) on it and measuring the result. Really, look in
// the LLVM sources. It does that. So this is likely similar to the ABI size
// (i.e. including alignment-padding), but goodness knows which alignment it
// winds up using. Probably the ABI one? Not recommended.
pub fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    unsafe {
        return llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMSizeOf(t),
                                      cx.int_type,
                                      False);
    }
}

// Returns the "default" size of t (see above), or 1 if the size would
// be zero.  This is important for things like vectors that expect
// space to be consumed.
pub fn nonzero_llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    if llbitsize_of_real(cx, t) == 0 {
        unsafe { llvm::LLVMConstInt(cx.int_type, 1, False) }
    } else {
        llsize_of(cx, t)
    }
}

// Returns the preferred alignment of the given type for the current target.
// The preffered alignment may be larger than the alignment used when
// packing the type into structs. This will be used for things like
// allocations inside a stack frame, which LLVM has a free hand in.
pub fn llalign_of_pref(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMPreferredAlignmentOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the minimum alignment of a type required by the plattform.
// This is the alignment that will be used for struct fields, arrays,
// and similar ABI-mandated things.
pub fn llalign_of_min(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMABIAlignmentOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the "default" alignment of t, which is calculated by casting
// null to a record containing a single-bit followed by a t value, then
// doing gep(0,1) to get at the trailing (and presumably padded) t cell.
pub fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    unsafe {
        return llvm::LLVMConstIntCast(
            lib::llvm::llvm::LLVMAlignOf(t), cx.int_type, False);
    }
}

// Computes the size of the data part of an enum.
pub fn static_size_of_enum(cx: @crate_ctxt, t: ty::t) -> uint {
    if cx.enum_sizes.contains_key_ref(&t) { return cx.enum_sizes.get(&t); }
    match ty::get(t).sty {
      ty::ty_enum(tid, ref substs) => {
        // Compute max(variant sizes).
        let mut max_size = 0u;
        let variants = ty::enum_variants(cx.tcx, tid);
        for vec::each(*variants) |variant| {
            let tup_ty = simplify_type(
                cx.tcx,
                ty::mk_tup(cx.tcx, /*bad*/copy variant.args));
            // Perform any type parameter substitutions.
            let tup_ty = ty::subst(cx.tcx, substs, tup_ty);
            // Here we possibly do a recursive call.
            let this_size =
                llsize_of_real(cx, type_of::type_of(cx, tup_ty));
            if max_size < this_size { max_size = this_size; }
        }
        cx.enum_sizes.insert(t, max_size);
        return max_size;
      }
      _ => cx.sess.bug(~"static_size_of_enum called on non-enum")
    }
}

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

// Information concerning the machine representation of various types.

use middle::trans::common::*;
use middle::trans::type_of;
use middle::ty::field;
use middle::ty;

use syntax::parse::token::special_idents;

// Creates a simpler, size-equivalent type. The resulting type is guaranteed
// to have (a) the same size as the type that was passed in; (b) to be non-
// recursive. This is done by replacing all boxes in a type with boxed unit
// types.
// This should reduce all pointers to some simple pointer type, to
// ensure that we don't recurse endlessly when computing the size of a
// nominal type that has pointers to itself in it.
pub fn simplify_type(tcx: ty::ctxt, typ: ty::t) -> ty::t {
    fn nilptr(tcx: ty::ctxt) -> ty::t {
        ty::mk_ptr(tcx, ty::mt {ty: ty::mk_nil(tcx), mutbl: ast::m_imm})
    }
    fn simplifier(tcx: ty::ctxt, typ: ty::t) -> ty::t {
        match ty::get(typ).sty {
          ty::ty_box(_) | ty::ty_opaque_box | ty::ty_uniq(_) |
          ty::ty_evec(_, ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_box) |
          ty::ty_estr(ty::vstore_uniq) | ty::ty_estr(ty::vstore_box) |
          ty::ty_ptr(_) | ty::ty_rptr(*) => nilptr(tcx),

          ty::ty_bare_fn(*) | // FIXME(#4804) Bare fn repr
          ty::ty_closure(*) => ty::mk_tup(tcx, ~[nilptr(tcx), nilptr(tcx)]),

          ty::ty_evec(_, ty::vstore_slice(_)) |
          ty::ty_estr(ty::vstore_slice(_)) => {
            ty::mk_tup(tcx, ~[nilptr(tcx), ty::mk_int(tcx)])
          }
          // Reduce a class type to a record type in which all the fields are
          // simplified
          ty::ty_struct(did, ref substs) => {
            let simpl_fields = (if ty::ty_dtor(tcx, did).is_present() {
                // remember the drop flag
                  ~[field {
                    ident: special_idents::dtor,
                    mt: ty::mt {ty: ty::mk_u8(tcx), mutbl: ast::m_mutbl}
                   }] }
                else { ~[] }) +
                do ty::lookup_struct_fields(tcx, did).map |f| {
                 let t = ty::lookup_field_type(tcx, did, f.id, substs);
                 field {
                    ident: f.ident,
                    mt: ty::mt {ty: simplify_type(tcx, t), mutbl: ast::m_const
                 }}
            };
            ty::mk_rec(tcx, simpl_fields)
          }
          _ => typ
        }
    }
    ty::fold_ty(tcx, typ, |t| simplifier(tcx, t))
}

// ______________________________________________________________________
// compute sizeof / alignof

pub type metrics = {
    bcx: block,
    sz: ValueRef,
    align: ValueRef
};

pub type tag_metrics = {
    bcx: block,
    sz: ValueRef,
    align: ValueRef,
    payload_align: ValueRef
};

// Returns the number of bytes clobbered by a Store to this type.
pub fn llsize_of_store(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMStoreSizeOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the number of bytes between successive elements of type T in an
// array of T. This is the "ABI" size. It includes any ABI-mandated padding.
pub fn llsize_of_alloc(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMABISizeOfType(cx.td.lltd, t) as uint;
    }
}

// Returns, as near as we can figure, the "real" size of a type. As in, the
// bits in this number of bytes actually carry data related to the datum
// with the type. Not junk, padding, accidentally-damaged words, or
// whatever. Rounds up to the nearest byte though, so if you have a 1-bit
// value, we return 1 here, not 0. Most of rustc works in bytes. Be warned
// that LLVM *does* distinguish between e.g. a 1-bit value and an 8-bit value
// at the codegen level! In general you should prefer `llbitsize_of_real`
// below.
pub fn llsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        let nbits = llvm::LLVMSizeOfTypeInBits(cx.td.lltd, t) as uint;
        if nbits & 7u != 0u {
            // Not an even number of bytes, spills into "next" byte.
            1u + (nbits >> 3)
        } else {
            nbits >> 3
        }
    }
}

/// Returns the "real" size of the type in bits.
pub fn llbitsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        llvm::LLVMSizeOfTypeInBits(cx.td.lltd, t) as uint
    }
}

/// Returns the size of the type as an LLVM constant integer value.
pub fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    // Once upon a time, this called LLVMSizeOf, which does a
    // getelementptr(1) on a null pointer and casts to an int, in
    // order to obtain the type size as a value without requiring the
    // target data layout.  But we have the target data layout, so
    // there's no need for that contrivance.  The instruction
    // selection DAG generator would flatten that GEP(1) node into a
    // constant of the type's alloc size, so let's save it some work.
    return C_uint(cx, llsize_of_alloc(cx, t));
}

// Returns the "default" size of t (see above), or 1 if the size would
// be zero.  This is important for things like vectors that expect
// space to be consumed.
pub fn nonzero_llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    if llbitsize_of_real(cx, t) == 0 {
        unsafe { llvm::LLVMConstInt(cx.int_type, 1, False) }
    } else {
        llsize_of(cx, t)
    }
}

// Returns the preferred alignment of the given type for the current target.
// The preffered alignment may be larger than the alignment used when
// packing the type into structs. This will be used for things like
// allocations inside a stack frame, which LLVM has a free hand in.
pub fn llalign_of_pref(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMPreferredAlignmentOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the minimum alignment of a type required by the plattform.
// This is the alignment that will be used for struct fields, arrays,
// and similar ABI-mandated things.
pub fn llalign_of_min(cx: @crate_ctxt, t: TypeRef) -> uint {
    unsafe {
        return llvm::LLVMABIAlignmentOfType(cx.td.lltd, t) as uint;
    }
}

// Returns the "default" alignment of t, which is calculated by casting
// null to a record containing a single-bit followed by a t value, then
// doing gep(0,1) to get at the trailing (and presumably padded) t cell.
pub fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
    unsafe {
        return llvm::LLVMConstIntCast(
            lib::llvm::llvm::LLVMAlignOf(t), cx.int_type, False);
    }
}

// Computes the size of the data part of an enum.
pub fn static_size_of_enum(cx: @crate_ctxt, t: ty::t) -> uint {
    if cx.enum_sizes.contains_key_ref(&t) { return cx.enum_sizes.get(&t); }
    match ty::get(t).sty {
      ty::ty_enum(tid, ref substs) => {
        // Compute max(variant sizes).
        let mut max_size = 0u;
        let variants = ty::enum_variants(cx.tcx, tid);
        for vec::each(*variants) |variant| {
            let tup_ty = simplify_type(
                cx.tcx,
                ty::mk_tup(cx.tcx, /*bad*/copy variant.args));
            // Perform any type parameter substitutions.
            let tup_ty = ty::subst(cx.tcx, substs, tup_ty);
            // Here we possibly do a recursive call.
            let this_size =
                llsize_of_real(cx, type_of::type_of(cx, tup_ty));
            if max_size < this_size { max_size = this_size; }
        }
        cx.enum_sizes.insert(t, max_size);
        return max_size;
      }
      _ => cx.sess.bug(~"static_size_of_enum called on non-enum")
    }
}

<|endoftext|>


<commit_before>use std::io;
use std::cmp;
use std::str;
use std::slice;
use std::io::IoResult;
use std::io::MemReader;

use colortype;
use hash::Crc32;
use zlib::ZlibDecoder;

use image;
use image::ImageResult;
use image::ImageDecoder;

use super::filter::unfilter;
use super::PNGSIGNATURE;

macro_rules! io_try(
    ($e:expr) => (
    	match $e {
    		Ok(e) => e,
    		Err(_) => return Err(image::IoError)
    	}
    )
)

#[deriving(PartialEq)]
enum PNGState {
	Start,
	HaveSignature,
	HaveIHDR,
	HavePLTE,
	HaveFirstIDat,
	HaveLastIDat,
	HaveIEND
}

/// The representation of a PNG decoder
///
/// Currently does not support decoding of interlaced images
pub struct PNGDecoder<R> {
	z: ZlibDecoder<IDATReader<R>>,
	crc: Crc32,
	previous: Vec<u8>,
	state: PNGState,

	width: u32,
	height: u32,

	bit_depth: u8,
	colour_type: u8,
	pixel_type: colortype::ColorType,

	palette: Option<Vec<(u8, u8, u8)>>,

	interlace_method: u8,

	chunk_length: u32,
	chunk_type: Vec<u8>,

	bpp: uint,
	rlength: uint,
	decoded_rows: u32,
}

impl<R: Reader> PNGDecoder<R> {
	/// Create a new decoder that decodes from the stream ```r```
	pub fn new(r: R) -> PNGDecoder<R> {
		let idat_reader = IDATReader::new(r);
		PNGDecoder {
			pixel_type: colortype::Grey(1),
			palette: None,

			previous: Vec::new(),
			state: Start,
			z: ZlibDecoder::new(idat_reader),
			crc: Crc32::new(),

			width: 0,
			height: 0,
			bit_depth: 0,
			colour_type: 0,
			interlace_method: 0,

			chunk_length: 0,
			chunk_type: Vec::new(),
			bpp: 0,
			rlength: 0,
			decoded_rows: 0,
		}
	}

	///Returns a reference to the color palette used for indexed
	///color images.
	///Each array element is a tuple of RGB values.
	pub fn palette<'a>(&'a self) -> &'a [(u8, u8, u8)] {
		match self.palette {
			Some(ref p) => p.as_slice(),
			None        => &[]
		}
	}

	fn read_signature(&mut self) -> ImageResult<bool> {
		let png = io_try!(self.z.inner().r.read_exact(8));

		Ok(png.as_slice() == PNGSIGNATURE)
	}

	fn parse_ihdr(&mut self, buf: Vec<u8>) -> ImageResult<()> {
		self.crc.update(buf.as_slice());
		let mut m = MemReader::new(buf);

		self.width = m.read_be_u32().unwrap();
		self.height = m.read_be_u32().unwrap();

		self.bit_depth = m.read_byte().unwrap();
		self.colour_type = m.read_byte().unwrap();

		self.pixel_type = match (self.colour_type, self.bit_depth) {
			(0, 1)  => colortype::Grey(1),
			(0, 2)  => colortype::Grey(2),
			(0, 4)  => colortype::Grey(4),
			(0, 8)  => colortype::Grey(8),
			(0, 16) => colortype::Grey(16),
			(2, 8)  => colortype::RGB(8),
			(2, 16) => colortype::RGB(16),
			(3, 1)  => colortype::RGB(8),
			(3, 2)  => colortype::RGB(8),
			(3, 4)  => colortype::RGB(8),
			(3, 8)  => colortype::RGB(8),
			(4, 8)  => colortype::GreyA(8),
			(4, 16) => colortype::GreyA(16),
			(6, 8)  => colortype::RGBA(8),
			(6, 16) => colortype::RGBA(16),
			(_, _)  => return Err(image::FormatError)
		};

		let compression_method = m.read_byte().unwrap();
		if compression_method != 0 {
			return Err(image::UnsupportedError)
		}

		let filter_method = m.read_byte().unwrap();
		if filter_method != 0 {
			return Err(image::UnsupportedError)
		}

		self.interlace_method = m.read_byte().unwrap();
		if self.interlace_method != 0 {
			return Err(image::UnsupportedError)
		}

		let channels = match self.colour_type {
			0 => 1,
			2 => 3,
			3 => 1,
			4 => 2,
			6 => 4,
			_ => return Err(image::FormatError)
		};

		let bits_per_pixel = channels * self.bit_depth as uint;

		self.rlength = (bits_per_pixel * self.width as uint + 7) / 8;
		self.bpp = (bits_per_pixel + 7) / 8;
		self.previous = Vec::from_elem(self.rlength as uint, 0u8);

		Ok(())
	}

	fn parse_plte(&mut self, buf: Vec<u8>) -> ImageResult<()> {
		self.crc.update(buf.as_slice());

		let len = buf.len() / 3;

		if len > 256 || len > (1 << self.bit_depth) || buf.len() % 3 != 0{
			return Err(image::FormatError)
		}

		let p = Vec::from_fn(256, |i| {
			if i < len {
				let r = buf.as_slice()[3 * i];
				let g = buf.as_slice()[3 * i + 1];
				let b = buf.as_slice()[3 * i + 2];

				(r, g, b)
			}
			else {
				(0, 0, 0)
			}
		});

		self.palette = Some(p);

		Ok(())
	}

	fn read_metadata(&mut self) -> ImageResult<()> {
		if !try!(self.read_signature()) {
			return Err(image::FormatError)
		}

		self.state = HaveSignature;

		loop {
			let length = io_try!(self.z.inner().r.read_be_u32());
			let chunk  = io_try!(self.z.inner().r.read_exact(4));

			self.chunk_length = length;
			self.chunk_type   = chunk.clone();

			self.crc.update(chunk);

			let s = {
				let a = str::from_utf8_owned(self.chunk_type.clone());
				a.unwrap()
			};

			match (s.as_slice(), self.state) {
				("IHDR", HaveSignature) => {
					if length != 13 {
						return Err(image::FormatError)
					}

					let d = io_try!(self.z.inner().r.read_exact(length as uint));
					try!(self.parse_ihdr(d));

					self.state = HaveIHDR;
				}

				("PLTE", HaveIHDR) => {
					let d = io_try!(self.z.inner().r.read_exact(length as uint));
					try!(self.parse_plte(d));
					self.state = HavePLTE;
				}

				("tRNS", HavePLTE) => {
					return Err(image::UnsupportedError)
				}

				("IDAT", HaveIHDR) if self.colour_type != 3 => {
					self.state = HaveFirstIDat;
					self.z.inner().set_inital_length(self.chunk_length);
					self.z.inner().crc.update(self.chunk_type.as_slice());

					break;
				}

				("IDAT", HavePLTE) if self.colour_type == 3 => {
					self.state = HaveFirstIDat;
					self.z.inner().set_inital_length(self.chunk_length);
					self.z.inner().crc.update(self.chunk_type.as_slice());

					break;
				}

				_ => {
					let b = io_try!(self.z.inner().r.read_exact(length as uint));
					self.crc.update(b);
				}
			}

			let chunk_crc = io_try!(self.z.inner().r.read_be_u32());
			let crc = self.crc.checksum();

			if crc != chunk_crc {
				return Err(image::FormatError)
			}

			self.crc.reset();
		}

		Ok(())
	}
}

impl<R: Reader> ImageDecoder for PNGDecoder<R> {
	fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		Ok((self.width, self.height))
	}

	fn colortype(&mut self) -> ImageResult<colortype::ColorType> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		Ok(self.pixel_type)
	}

	fn row_len(&mut self) -> ImageResult<uint> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let bits = colortype::bits_per_pixel(self.pixel_type);

		Ok((bits * self.width as uint + 7) / 8)
	}

	fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let filter_type = match FromPrimitive::from_u8(io_try!(self.z.read_byte())) {
			Some(v) => v,
			_ => return Err(image::FormatError)
		};

		let mut read = 0;
		while read < self.rlength {
			let r = io_try!(self.z.read(buf.mut_slice_from(read)));
			read += r;
		}

		unfilter(filter_type, self.bpp, self.previous.as_slice(), buf.mut_slice_to(self.rlength));
		slice::bytes::copy_memory(self.previous.as_mut_slice(), buf.slice_to(self.rlength));

		if self.palette.is_some() {
			let s = (*self.palette.get_ref()).as_slice();
			expand_palette(buf, s, self.rlength);
		}

		self.decoded_rows += 1;

		Ok(self.decoded_rows)
	}

	fn read_image(&mut self) -> ImageResult<Vec<u8>> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let rowlen  = try!(self.row_len());
		let mut buf = Vec::from_elem(rowlen * self.height as uint, 0u8);

		for chunk in buf.as_mut_slice().mut_chunks(rowlen) {
			let _ = try!(self.read_scanline(chunk));
		}

		Ok(buf)
	}
}

fn expand_palette(buf: &mut[u8], palette: &[(u8, u8, u8)], entries: uint) {
	assert!(buf.len() == entries * 3);
	let tmp = Vec::from_fn(entries, |i| buf[i]);

	for (chunk, &i) in buf.mut_chunks(3).zip(tmp.iter()) {
		let (r, g, b) = palette[i as uint];
		chunk[0] = r;
		chunk[1] = g;
		chunk[2] = b;
	}
}

pub struct IDATReader<R> {
	pub r: R,
	pub crc: Crc32,

	eof: bool,
	chunk_length: u32,
}

impl<R:Reader> IDATReader<R> {
	pub fn new(r: R) -> IDATReader<R> {
		IDATReader {
			r: r,
			crc: Crc32::new(),
			eof: false,
			chunk_length: 0,
		}
	}

	pub fn set_inital_length(&mut self, len: u32) {
		self.chunk_length = len;
	}
}

impl<R: Reader> Reader for IDATReader<R> {
	fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
		if self.eof {
			return Err(io::standard_error(io::EndOfFile))
		}

		let len = buf.len();
		let mut start = 0;

		while start < len {
			let m = cmp::min(len - start, self.chunk_length as uint);

			let slice = buf.mut_slice(start, start + m);
			let r = try!(self.r.read(slice));

			start += r;

			self.chunk_length -= r as u32;
			self.crc.update(slice.as_slice());

			if self.chunk_length == 0 {
				let chunk_crc = try!(self.r.read_be_u32());
				let crc = self.crc.checksum();
				if crc != chunk_crc {
					return Err(io::standard_error(io::InvalidInput))
				}

				self.crc.reset();

				self.chunk_length = try!(self.r.read_be_u32());

				let v = try!(self.r.read_exact(4));
				self.crc.update(v.as_slice());

				match str::from_utf8(v.as_slice()) {
					Some("IDAT") => (),
					_ 	     => {
						self.eof = true;
						break
					}
				}
			}
		}
		Ok(start)
	}
}<commit_msg>Prevent failure on strange chunk types<commit_after>use std::io;
use std::cmp;
use std::str;
use std::slice;
use std::io::IoResult;
use std::io::MemReader;

use colortype;
use hash::Crc32;
use zlib::ZlibDecoder;

use image;
use image::ImageResult;
use image::ImageDecoder;

use super::filter::unfilter;
use super::PNGSIGNATURE;

macro_rules! io_try(
    ($e:expr) => (
    	match $e {
    		Ok(e) => e,
    		Err(_) => return Err(image::IoError)
    	}
    )
)

#[deriving(PartialEq)]
enum PNGState {
	Start,
	HaveSignature,
	HaveIHDR,
	HavePLTE,
	HaveFirstIDat,
	HaveLastIDat,
	HaveIEND
}

/// The representation of a PNG decoder
///
/// Currently does not support decoding of interlaced images
pub struct PNGDecoder<R> {
	z: ZlibDecoder<IDATReader<R>>,
	crc: Crc32,
	previous: Vec<u8>,
	state: PNGState,

	width: u32,
	height: u32,

	bit_depth: u8,
	colour_type: u8,
	pixel_type: colortype::ColorType,

	palette: Option<Vec<(u8, u8, u8)>>,

	interlace_method: u8,

	chunk_length: u32,
	chunk_type: Vec<u8>,

	bpp: uint,
	rlength: uint,
	decoded_rows: u32,
}

impl<R: Reader> PNGDecoder<R> {
	/// Create a new decoder that decodes from the stream ```r```
	pub fn new(r: R) -> PNGDecoder<R> {
		let idat_reader = IDATReader::new(r);
		PNGDecoder {
			pixel_type: colortype::Grey(1),
			palette: None,

			previous: Vec::new(),
			state: Start,
			z: ZlibDecoder::new(idat_reader),
			crc: Crc32::new(),

			width: 0,
			height: 0,
			bit_depth: 0,
			colour_type: 0,
			interlace_method: 0,

			chunk_length: 0,
			chunk_type: Vec::new(),
			bpp: 0,
			rlength: 0,
			decoded_rows: 0,
		}
	}

	///Returns a reference to the color palette used for indexed
	///color images.
	///Each array element is a tuple of RGB values.
	pub fn palette<'a>(&'a self) -> &'a [(u8, u8, u8)] {
		match self.palette {
			Some(ref p) => p.as_slice(),
			None        => &[]
		}
	}

	fn read_signature(&mut self) -> ImageResult<bool> {
		let png = io_try!(self.z.inner().r.read_exact(8));

		Ok(png.as_slice() == PNGSIGNATURE)
	}

	fn parse_ihdr(&mut self, buf: Vec<u8>) -> ImageResult<()> {
		self.crc.update(buf.as_slice());
		let mut m = MemReader::new(buf);

		self.width = m.read_be_u32().unwrap();
		self.height = m.read_be_u32().unwrap();

		self.bit_depth = m.read_byte().unwrap();
		self.colour_type = m.read_byte().unwrap();

		self.pixel_type = match (self.colour_type, self.bit_depth) {
			(0, 1)  => colortype::Grey(1),
			(0, 2)  => colortype::Grey(2),
			(0, 4)  => colortype::Grey(4),
			(0, 8)  => colortype::Grey(8),
			(0, 16) => colortype::Grey(16),
			(2, 8)  => colortype::RGB(8),
			(2, 16) => colortype::RGB(16),
			(3, 1)  => colortype::RGB(8),
			(3, 2)  => colortype::RGB(8),
			(3, 4)  => colortype::RGB(8),
			(3, 8)  => colortype::RGB(8),
			(4, 8)  => colortype::GreyA(8),
			(4, 16) => colortype::GreyA(16),
			(6, 8)  => colortype::RGBA(8),
			(6, 16) => colortype::RGBA(16),
			(_, _)  => return Err(image::FormatError)
		};

		let compression_method = m.read_byte().unwrap();
		if compression_method != 0 {
			return Err(image::UnsupportedError)
		}

		let filter_method = m.read_byte().unwrap();
		if filter_method != 0 {
			return Err(image::UnsupportedError)
		}

		self.interlace_method = m.read_byte().unwrap();
		if self.interlace_method != 0 {
			return Err(image::UnsupportedError)
		}

		let channels = match self.colour_type {
			0 => 1,
			2 => 3,
			3 => 1,
			4 => 2,
			6 => 4,
			_ => return Err(image::FormatError)
		};

		let bits_per_pixel = channels * self.bit_depth as uint;

		self.rlength = (bits_per_pixel * self.width as uint + 7) / 8;
		self.bpp = (bits_per_pixel + 7) / 8;
		self.previous = Vec::from_elem(self.rlength as uint, 0u8);

		Ok(())
	}

	fn parse_plte(&mut self, buf: Vec<u8>) -> ImageResult<()> {
		self.crc.update(buf.as_slice());

		let len = buf.len() / 3;

		if len > 256 || len > (1 << self.bit_depth) || buf.len() % 3 != 0{
			return Err(image::FormatError)
		}

		let p = Vec::from_fn(256, |i| {
			if i < len {
				let r = buf.as_slice()[3 * i];
				let g = buf.as_slice()[3 * i + 1];
				let b = buf.as_slice()[3 * i + 2];

				(r, g, b)
			}
			else {
				(0, 0, 0)
			}
		});

		self.palette = Some(p);

		Ok(())
	}

	fn read_metadata(&mut self) -> ImageResult<()> {
		if !try!(self.read_signature()) {
			return Err(image::FormatError)
		}

		self.state = HaveSignature;

		loop {
			let length = io_try!(self.z.inner().r.read_be_u32());
			let chunk  = io_try!(self.z.inner().r.read_exact(4));

			self.chunk_length = length;
			self.chunk_type   = chunk.clone();

			self.crc.update(chunk);

			let s =  str::from_utf8_owned(self.chunk_type.clone())
				.unwrap_or(String::from_str(""));

			match (s.as_slice(), self.state) {
				("IHDR", HaveSignature) => {
					if length != 13 {
						return Err(image::FormatError)
					}

					let d = io_try!(self.z.inner().r.read_exact(length as uint));
					try!(self.parse_ihdr(d));

					self.state = HaveIHDR;
				}

				("PLTE", HaveIHDR) => {
					let d = io_try!(self.z.inner().r.read_exact(length as uint));
					try!(self.parse_plte(d));
					self.state = HavePLTE;
				}

				("tRNS", HavePLTE) => {
					return Err(image::UnsupportedError)
				}

				("IDAT", HaveIHDR) if self.colour_type != 3 => {
					self.state = HaveFirstIDat;
					self.z.inner().set_inital_length(self.chunk_length);
					self.z.inner().crc.update(self.chunk_type.as_slice());

					break;
				}

				("IDAT", HavePLTE) if self.colour_type == 3 => {
					self.state = HaveFirstIDat;
					self.z.inner().set_inital_length(self.chunk_length);
					self.z.inner().crc.update(self.chunk_type.as_slice());

					break;
				}

				_ => {
					let b = io_try!(self.z.inner().r.read_exact(length as uint));
					self.crc.update(b);
				}
			}

			let chunk_crc = io_try!(self.z.inner().r.read_be_u32());
			let crc = self.crc.checksum();

			if crc != chunk_crc {
				return Err(image::FormatError)
			}

			self.crc.reset();
		}

		Ok(())
	}
}

impl<R: Reader> ImageDecoder for PNGDecoder<R> {
	fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		Ok((self.width, self.height))
	}

	fn colortype(&mut self) -> ImageResult<colortype::ColorType> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		Ok(self.pixel_type)
	}

	fn row_len(&mut self) -> ImageResult<uint> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let bits = colortype::bits_per_pixel(self.pixel_type);

		Ok((bits * self.width as uint + 7) / 8)
	}

	fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let filter_type = match FromPrimitive::from_u8(io_try!(self.z.read_byte())) {
			Some(v) => v,
			_ => return Err(image::FormatError)
		};

		let mut read = 0;
		while read < self.rlength {
			let r = io_try!(self.z.read(buf.mut_slice_from(read)));
			read += r;
		}

		unfilter(filter_type, self.bpp, self.previous.as_slice(), buf.mut_slice_to(self.rlength));
		slice::bytes::copy_memory(self.previous.as_mut_slice(), buf.slice_to(self.rlength));

		if self.palette.is_some() {
			let s = (*self.palette.get_ref()).as_slice();
			expand_palette(buf, s, self.rlength);
		}

		self.decoded_rows += 1;

		Ok(self.decoded_rows)
	}

	fn read_image(&mut self) -> ImageResult<Vec<u8>> {
		if self.state == Start {
			let _ = try!(self.read_metadata());
		}

		let rowlen  = try!(self.row_len());
		let mut buf = Vec::from_elem(rowlen * self.height as uint, 0u8);

		for chunk in buf.as_mut_slice().mut_chunks(rowlen) {
			let _ = try!(self.read_scanline(chunk));
		}

		Ok(buf)
	}
}

fn expand_palette(buf: &mut[u8], palette: &[(u8, u8, u8)], entries: uint) {
	assert!(buf.len() == entries * 3);
	let tmp = Vec::from_fn(entries, |i| buf[i]);

	for (chunk, &i) in buf.mut_chunks(3).zip(tmp.iter()) {
		let (r, g, b) = palette[i as uint];
		chunk[0] = r;
		chunk[1] = g;
		chunk[2] = b;
	}
}

pub struct IDATReader<R> {
	pub r: R,
	pub crc: Crc32,

	eof: bool,
	chunk_length: u32,
}

impl<R:Reader> IDATReader<R> {
	pub fn new(r: R) -> IDATReader<R> {
		IDATReader {
			r: r,
			crc: Crc32::new(),
			eof: false,
			chunk_length: 0,
		}
	}

	pub fn set_inital_length(&mut self, len: u32) {
		self.chunk_length = len;
	}
}

impl<R: Reader> Reader for IDATReader<R> {
	fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
		if self.eof {
			return Err(io::standard_error(io::EndOfFile))
		}

		let len = buf.len();
		let mut start = 0;

		while start < len {
			let m = cmp::min(len - start, self.chunk_length as uint);

			let slice = buf.mut_slice(start, start + m);
			let r = try!(self.r.read(slice));

			start += r;

			self.chunk_length -= r as u32;
			self.crc.update(slice.as_slice());

			if self.chunk_length == 0 {
				let chunk_crc = try!(self.r.read_be_u32());
				let crc = self.crc.checksum();
				if crc != chunk_crc {
					return Err(io::standard_error(io::InvalidInput))
				}

				self.crc.reset();

				self.chunk_length = try!(self.r.read_be_u32());

				let v = try!(self.r.read_exact(4));
				self.crc.update(v.as_slice());

				match str::from_utf8(v.as_slice()) {
					Some("IDAT") => (),
					_ 	     => {
						self.eof = true;
						break
					}
				}
			}
		}
		Ok(start)
	}
}<|endoftext|>


<commit_before><commit_msg>Work on ReadItem.<commit_after><|endoftext|>


<commit_before><commit_msg>fix: adding exec module<commit_after>
extern crate notify;
extern crate yaml_rust;
extern crate glob;

use std::{thread, time};
use std::process::Command as ShellCommand;
use std::error::Error;

use self::notify::{RecommendedWatcher, Watcher};
use self::yaml_rust::{Yaml, YamlLoader};

use cli::Command;
use yaml;

pub const FILENAME: &'static str = ".watch.yaml";

/// # `ExecCommand`
///
/// Executes commands in an interval of time
///
pub struct ExecCommand {
    command: String,
    interval: u64,
}

impl ExecCommand {
    pub fn new(command: String, interval: u64) -> Self {
        ExecCommand { command: command, interval: interval }
    }
}

impl Command for ExecCommand {
    fn execute(&self) -> Result<(), String> {
        let mut command = ShellCommand::new(&self.command);
        loop {
            if let Err(error) = command.status() {
                return Err(String::from(error.description()));
            }
            let wait = time::Duration::from_secs(self.interval);
            thread::sleep(wait)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[x86_all] started on BDA<commit_after>//
//  SOS: the Stupid Operating System
//  by Eliza Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2016 Eliza Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! BIOS Data Area
//!
//! see [the OS Dev Wiki]
//! (http://wiki.osdev.org/Memory_Map_(x86)#BIOS_Data_Area_.28BDA.29)
//! for more information.

const PORTS_ADDR: 0x0400;

/// BIOS Data Area that stores the addresses of serial and parallel ports
pub static PORTS: *const Ports
    = unsafe { PORTS_ADDR as *const PORTS };

/// Addresses of ports stored in the BIOS Data Area.
///
#[repr(C)]
pub struct Ports {
    /// Addresses of the `COM1`, `COM2`, `COM3`, and `COM4` serial ports
    pub com_ports: [u16; 4]
  , /// Addresses of the `LPT1`, `LPT2`, and `LPT3` parallel ports
    pub lpt_ports: [u16, 3]
}
<|endoftext|>


<commit_before><commit_msg>docs: updates documentation for v2 release<commit_after><|endoftext|>


<commit_before><commit_msg>me: make content mut<commit_after><|endoftext|>


<commit_before><commit_msg>Add object module<commit_after>use opengl_graphics::*;
use core::{Vec2};

/// A trait for positioned objects
pub trait Positioned {
  /// Get the x coordinate
  fn get_pos(&self) -> Vec2<i64>;
  /// Set the Vec coordinate
  fn set_pos(&mut self, new_pos: Vec2<i64>);
}

/// The direction of a given object
#[derive(Clone, Copy)]
pub enum Dir {
  Left,
  Right,
  Up,
  Down,
}
impl Dir {
  fn to_vec(&self) -> Vec2<i64> {
    Vec2(
      match *self {
        Dir::Left => 1,
        Dir::Right => -1,
        _ => 0,
      },

      match *self {
        Dir::Up => 1,
        Dir::Down => -1,
      _ => 0,
      }
    )
  }
}

// TODO: Implement two directions at once.
// TODO: Make drawable trait

/// A movable object
pub trait Movable: Positioned {
  /// Get the direction
  fn get_dir(&self) -> Dir;
  /// Set the direction
  fn set_dir(&mut self, new_dir: Dir);
  /// Is the object moving?
  fn is_moving(&self) -> bool;
  /// Move the object
  fn move_obj(&mut self, mov: Vec2<i64>) {
    let coord = self.get_pos();
    self.set_pos(coord + mov);
  }
  /// Get new coordinate
  fn get_new_pos(&self) -> Vec2<i64> {
    let dir = self.get_dir();
    self.get_pos() + dir.to_vec()
  }
  /// Move object in direction.
  fn move_obj_dir(&mut self) {
    let new_coord = self.get_new_pos();
    self.set_pos(new_coord)
  }
}

/// Trait for animated objects
pub trait Animated: Movable {
  /// Get transitition point, which is in the interval [0,1]
  fn get_trans_state(&self) -> f64;
  /// Get animation frame
  fn get_animation_frame(&self) -> i16;
}

/// Trait for sprited objects
pub trait Sprited: Animated {
  /// Get current sprite
  fn get_sprite(&self) -> &Texture;
  /// Get width, not neccesarily the width of the sprite, but rather the space
  /// the given object occupies. Given in fields.
  fn get_width(&self) -> i16;
  /// Get height, see note above
  fn get_height(&self) -> i16;
  /// Get the opacity of the object
  fn get_opacity(&self) -> f64;

  // TODO: Add draw method.
}

// TODO: Add event trait, for objects you can click on etc.

/// Entity ID type
pub struct Id(pub i64);

/// An entity
pub trait Entity: Sprited {
  /// Get the ID of the given entity
  fn id(&self) -> Id;
  /// Is the entity solid at point (x, y) relative to the position?
  fn is_solid(&self, x: i16, y: i16) -> bool;
  /// Update the entity
  fn update(&mut self, dt: f64);
  // Probably need more methods.
}
<|endoftext|>


<commit_before><commit_msg>What's a Manag?<commit_after><|endoftext|>


<commit_before><commit_msg>First draft of a libinput backend<commit_after>//! Implementation of input backend trait for types provided by `libinput`

use backend::SeatInternal;
use backend::input::{InputBackend, InputHandler, Seat, SeatCapabilities};
use input::{Libinput, Device, Seat as LibinputSeat, DeviceCapability};
use input::event::*;

use std::io::Error as IoError;
use std::collections::hash_map::{DefaultHasher, HashMap};
use std::hash::{Hash, Hasher};

pub struct LibinputInputBackend {
    context: Libinput,
    devices: Vec<Device>,
    seats: HashMap<LibinputSeat, Seat>,
    handler: Option<Box<InputHandler<LibinputInputBackend> + 'static>>,
}

impl InputBackend for LibinputInputBackend {
    type InputConfig = [Device];
    type EventError = IoError;

    fn set_handler<H: InputHandler<Self> + 'static>(&mut self, mut handler: H) {
        if self.handler.is_some() {
            self.clear_handler();
        }
        for seat in self.seats.values() {
            handler.on_seat_created(&seat);
        }
        self.handler = Some(Box::new(handler));
    }

    fn get_handler(&mut self) -> Option<&mut InputHandler<Self>> {
        self.handler
            .as_mut()
            .map(|handler| handler as &mut InputHandler<Self>)
    }

    fn clear_handler(&mut self) {
        if let Some(mut handler) = self.handler.take() {
            for seat in self.seats.values() {
                handler.on_seat_destroyed(&seat);
            }
        }
    }

    fn input_config(&mut self) -> &mut Self::InputConfig {
        &mut self.devices
    }

    fn set_cursor_position(&mut self, _x: u32, _y: u32) -> Result<(), ()> {
        // FIXME later.
        // This will be doable with the hardware cursor api and probably some more cases
        Err(())
    }

    fn dispatch_new_events(&mut self) -> Result<(), IoError> {
        self.context.dispatch()?;
        for event in &mut self.context {
            match event {
                Event::Device(device_event) => {
                    use input::event::device::*;
                    match device_event {
                        DeviceEvent::Added(device_added_event) => {
                            let added = device_added_event.into_event().device();

                            let new_caps = SeatCapabilities {
                                pointer: added.has_capability(DeviceCapability::Pointer),
                                keyboard: added.has_capability(DeviceCapability::Keyboard),
                                touch: added.has_capability(DeviceCapability::Touch),
                            };

                            let device_seat = added.seat();
                            self.devices.push(added);

                            let contains = self.seats.contains_key(&device_seat);
                            if contains {
                                let old_seat = self.seats.get_mut(&device_seat).unwrap();
                                {
                                    let caps = old_seat.capabilities_mut();
                                    caps.pointer = new_caps.pointer || caps.pointer;
                                    caps.keyboard = new_caps.keyboard || caps.keyboard;
                                    caps.touch = new_caps.touch || caps.touch;
                                }
                                if let Some(ref mut handler) = self.handler {
                                    handler.on_seat_changed(old_seat);
                                }
                            } else {
                                let mut hasher = DefaultHasher::default();
                                device_seat.hash(&mut hasher);
                                self.seats.insert(device_seat.clone(), Seat::new(hasher.finish(), new_caps));
                                if let Some(ref mut handler) = self.handler {
                                    handler.on_seat_created(self.seats.get(&device_seat).unwrap());
                                }
                            }
                        },
                        DeviceEvent::Removed(device_removed_event) => {
                            let removed = device_removed_event.into_event().device();

                            // remove device
                            self.devices.retain(|dev| *dev == removed);

                            let device_seat = removed.seat();

                            // update capabilities, so they appear correctly on `on_seat_changed` and `on_seat_destroyed`.
                            if let Some(seat) = self.seats.get_mut(&device_seat) {
                                let caps = seat.capabilities_mut();
                                caps.pointer = self.devices.iter().any(|x| x.has_capability(DeviceCapability::Pointer));
                                caps.keyboard = self.devices.iter().any(|x| x.has_capability(DeviceCapability::Keyboard));
                                caps.touch = self.devices.iter().any(|x| x.has_capability(DeviceCapability::Touch));
                            } else {
                                //TODO is this the best we can do?
                                panic!("Seat changed that was never created")
                            }

                            // check if the seat has any other devices
                            if !self.devices.iter().any(|x| x.seat() == device_seat) {
                                // it has not, lets destroy it
                                if let Some(seat) = self.seats.remove(&device_seat) {
                                    if let Some(ref mut handler) = self.handler {
                                        handler.on_seat_destroyed(&seat);
                                    }
                                } else {
                                    //TODO is this the best we can do?
                                    panic!("Seat destroyed that was never created");
                                }
                            } else {
                                // it has, notify about updates
                                if let Some(ref mut handler) = self.handler {
                                    handler.on_seat_changed(self.seats.get(&device_seat).unwrap());
                                }
                            }
                        },
                    }
                    if let Some(ref mut handler) = self.handler {
                       handler.on_input_config_changed(&mut self.devices);
                    }
                },
                Event::Touch(touch_event) => {},
                Event::Keyboard(keyboard_event) => {},
                Event::Pointer(pointer_event) => {},
                _ => {}, //FIXME: What to do with the rest.
            }
        };
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>src/api.rs: just copy of entropy.rs<commit_after>
mod api {

	pub type Target = u32;
	pub type Number = f64;
	pub type Category = u32;

	pub struct DataSet<T> {
		pub records: Vec<(T, Target)>,
		pub target_count: usize
	}

	pub enum FeatureType {
		Boolean,
		Category,
		Number
	}

	pub trait RecordMeta {

		fn feature_count(&self) -> usize;

		fn feature_name(&self, feature: usize) -> String;
		fn feature_type(&self, feature: usize) -> FeatureType;

		fn category_count(&self, feature: usize) -> usize;

	}

}

mod data {

	use ::api;

	pub struct Record {
		pub category: api::Category,
		pub number: api::Number,
		pub boolean: bool
	}

	impl api::RecordMeta for Record {

		fn feature_count(&self) -> usize {
			3
		}

		fn feature_name(&self, feature: usize) -> String {
			match feature {
				0 => "category".to_string(),
				1 => "number".to_string(),
				2 => "boolean".to_string(),
				_ => panic!("Unknown feature")
			}
		}

		fn feature_type(&self, feature: usize) -> api::FeatureType {
			match feature {
				0 => api::FeatureType::Category,
				1 => api::FeatureType::Number,
				2 => api::FeatureType::Boolean,
				_ => panic!("Unknown feature")
			}
		}

		fn category_count(&self, feature: usize) -> usize {
			match feature {
				0 => 3,
				_ => panic!("Unknown feature")
			}

		}

	}

	pub fn read_data() -> api::DataSet<Record> {
		let result = api::DataSet{
			records: vec![
				(Record{category: 0, number: 70.0, boolean: true }, 0),
				(Record{category: 0, number: 90.0, boolean: true }, 1),
				(Record{category: 0, number: 85.0, boolean: false}, 1),
				(Record{category: 0, number: 95.0, boolean: false}, 1),
				(Record{category: 0, number: 70.0, boolean: false}, 0),
				(Record{category: 1, number: 90.0, boolean: true }, 0),
				(Record{category: 1, number: 78.0, boolean: false}, 0),
				(Record{category: 1, number: 65.0, boolean: true }, 0),
				(Record{category: 1, number: 75.0, boolean: false}, 0),
				(Record{category: 2, number: 80.0, boolean: true }, 1),
				(Record{category: 2, number: 70.0, boolean: true }, 1),
				(Record{category: 2, number: 80.0, boolean: false}, 0),
				(Record{category: 2, number: 80.0, boolean: false}, 0),
				(Record{category: 2, number: 96.0, boolean: false}, 0)
			],
			target_count: 2
		};
		result
	}

}

mod solve_func {

	use ::api;

	pub fn information_gain<T: api::RecordMeta, F>(data: &api::DataSet<T>, criterion: &F) -> f64 where F: Fn(&T) -> bool {
		let e = target_entropy(data);
		let fe = entropy(data, criterion);
		e - fe
	}

	fn entropy_helper<T: api::RecordMeta, F>(data: &api::DataSet<T>, value: bool, criterion: &F) -> f64 where F: Fn(&T) -> bool {
		let mut total = 0;
		let mut classes = vec![0; data.target_count];
		for record in data.records.iter() {
			if criterion(&record.0) == value {
				classes[record.1 as usize] += 1;
				total += 1;
			}
		}
		let mut result = 0f64;
		for class in classes.iter() {
			if *class != 0 {
				let p = (*class as f64) / (total as f64);
				result += p * p.log2()
			}
		}
		-result
	}

	fn entropy<T: api::RecordMeta, F>(data: &api::DataSet<T>, criterion: &F) -> f64 where F: Fn(&T) -> bool {
		let total = data.records.len();
		let mut ccs = vec![0u8, 0u8];
		let values = vec![false, true];
		for record in data.records.iter() {
			let i = match criterion(&record.0) {
					false => 0,
					true => 1,
			};
			ccs[i] += 1;
		}
		let mut result = 0f64;
		for i in 0..2 {
			let p = (ccs[i] as f64) / (total as f64);
			result += p * entropy_helper(data, values[i], criterion);
		}
		result
	}

	fn target_entropy<T: api::RecordMeta>(data: &api::DataSet<T>) -> f64 {
		let total = data.records.len();
		let mut classes = vec![0; data.target_count];
		for record in data.records.iter() {
			classes[record.1 as usize] += 1;
		}
		for class in classes.iter() {
			if *class == 0 {
				return 0f64
			}
		}
		let mut result = 0f64;
		for class in classes.iter() {
			let p = (*class as f64) / (total as f64);
			result += p * p.log2()
		}
		-result
	}

}

fn main() {
	println!("Hello, ID3!");
	let data = data::read_data();
	let entropy = solve_func::information_gain(&data, &|rec| rec.boolean);
	println!("{}", entropy);
}
<|endoftext|>


<commit_before><commit_msg>Removed unused imports in test.<commit_after><|endoftext|>


<commit_before><commit_msg>f55 f65 opcodes<commit_after><|endoftext|>


<commit_before><commit_msg>Method names<commit_after><|endoftext|>


<commit_before><commit_msg>Add method to generate the next generation<commit_after><|endoftext|>


<commit_before><commit_msg>Change 'deriving' to 'derive'; fix warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #490 - redox-os:master, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>whoops need this too<commit_after>use std;
use std::io::{File, Open, ReadWrite,
              TempDir, Command, SeekSet};
use time::{get_time};
use std::os::{getenv};
use errors::{ThecaError, GenericError};
use std::io::process::{InheritFd};
use term;
use term::attr::Attr::{Bold};

pub use libc::{
    STDIN_FILENO,
    STDOUT_FILENO,
    STDERR_FILENO
};

// c calls for TIOCGWINSZ
mod c {
    extern crate libc;
    pub use self::libc::{
        c_int,
        c_ushort,
        c_ulong,
        STDOUT_FILENO
    };
    use std::mem::zeroed;
    pub struct Winsize {
        pub ws_row: c_ushort,
        pub ws_col: c_ushort
    }
    #[cfg(any(target_os = "linux", target_os = "android"))]
    static TIOCGWINSZ: c_ulong = 0x5413;
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    static TIOCGWINSZ: c_ulong = 0x40087468;
    extern {
        pub fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
    }
    pub unsafe fn dimensions() -> Winsize {
        let mut window: Winsize = zeroed();
        ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window as *mut Winsize);
        window
    }
}

// unsafety wrapper
pub fn termsize() -> usize {
    let ws = unsafe {c::dimensions()};
    if ws.ws_col == 0 || ws.ws_row == 0 {
        0
    }
    else {
        ws.ws_col as usize
    }
}

pub fn drop_to_editor(contents: &String) -> Result<String, ThecaError> {
    // setup temporary directory
    let tmpdir = try!(TempDir::new("theca"));
    // setup temporary file to write/read
    let tmppath = tmpdir.path().join(get_time().sec.to_string());
    let mut tmpfile = try!(File::open_mode(&tmppath, Open, ReadWrite));
    try!(tmpfile.write_line(contents.as_slice()));
    // we now have a temp file, at `tmppath`, that contains `contents`
    // first we need to know which onqe
    let editor = match getenv("VISUAL") {
        Some(val) => val,
        None => {
            match getenv("EDITOR") {
                Some(val) => val,
                None => specific_fail!("neither $VISUAL nor $EDITOR is set.".to_string())
            }
        }
    };
    // lets start `editor` and edit the file at `tmppath`
    // first we need to set STDIN, STDOUT, and STDERR to those that theca is
    // currently using so we can display the editor
    let mut editor_command = Command::new(editor);
    editor_command.arg(tmppath.display().to_string());
    editor_command.stdin(InheritFd(STDIN_FILENO));
    editor_command.stdout(InheritFd(STDOUT_FILENO));
    editor_command.stderr(InheritFd(STDERR_FILENO));
    let editor_proc = editor_command.spawn();
    match try!(editor_proc).wait().is_ok() {
        true => {
            // finished editing, time to read `tmpfile` for the final output
            // seek to start of `tmpfile`
            try!(tmpfile.seek(0, SeekSet));
            Ok(try!(tmpfile.read_to_string()))
        }
        false => specific_fail!("The editor broke... I think".to_string())
    }
}

pub fn get_password() -> Result<String, ThecaError> {
    // should really turn off terminal echo...
    print!("Key: ");
    let mut stdin = std::io::stdio::stdin();
    // since this only reads one line of stdin it could still feasibly
    // be used with `-` to set note body?
    let key = try!(stdin.read_line());
    Ok(key.trim().to_string())
}

pub fn pretty_line(bold: &str, plain: &String, color: bool) -> Result<(), ThecaError> {
    let mut t = match term::stdout() {
        Some(t) => t,
        None => specific_fail!("could not retrieve standard output.".to_string())
    };
    if color {try!(t.attr(Bold));}
    try!(write!(t, "{}", bold.to_string()));
    if color {try!(t.reset());}
    try!(write!(t, "{}", plain));
    Ok(())
}

pub fn format_field(value: &String, width: usize, truncate: bool) -> String {
    if value.len() > width && width > 3 && truncate {
        format!("{: <1$.1$}...", value, width-3)
    } else {
        format!("{: <1$.1$}", value, width)
    }
}

<|endoftext|>


<commit_before><commit_msg>Add an inlining debuginfo test<commit_after>#![crate_type="rlib"]
// compile-flags: -Copt-level=3 -g

#[no_mangle]
#[inline(always)]
pub extern "C" fn callee(x: u32) -> u32 {
    x + 4
}

// CHECK-LABEL: caller
// CHECK: call void @llvm.dbg.value(metadata i32 %y, metadata !{{.*}}, metadata !DIExpression(DW_OP_constu, 3, DW_OP_minus, DW_OP_stack_value)), !dbg [[A:!.*]]
// CHECK: [[A]] = !DILocation(line: {{.*}}, scope: {{.*}}, inlinedAt: {{.*}})
#[no_mangle]
pub extern "C" fn caller(y: u32) -> u32 {
    callee(y - 3)
}
<|endoftext|>


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

mod foo {
    pub use bar::*;
    pub use main as f; //~ ERROR has already been imported
}

mod bar {
    pub use foo::*;
}

pub use foo::*;
pub use baz::*; //~ ERROR has already been imported
mod baz {
    pub use super::*;
}

pub fn main() {}
<|endoftext|>