<commit_before>use std::mem;
use std::slice;
use std::default::Default;
use std::iter::CloneableIterator;

use color;
use color:: {
    Pixel,
    ColorType
};

/// An enumeration of Image Errors
#[deriving(Show, PartialEq, Eq)]
pub enum ImageError {
    ///The Image is not formatted properly
    FormatError,

    ///The Image's dimensions are either too small or too large
    DimensionError,

    ///The Decoder does not support this image format
    UnsupportedError,

    ///The Decoder does not support this color type
    UnsupportedColor,

    ///Not enough data was provided to the Decoder
    ///to decode the image
    NotEnoughData,

    ///An I/O Error occurred while decoding the image
    IoError,

    ///The end of the image has been reached
    ImageEnd
}

pub type ImageResult<T> = Result<T, ImageError>;

/// An enumeration of supported image formats.
/// Not all formats support both encoding and decoding.
#[deriving(PartialEq, Eq, Show)]
pub enum ImageFormat {
    /// An Image in PNG Format
    PNG,

    /// An Image in JPEG Format
    JPEG,

    /// An Image in GIF Format
    GIF,

    /// An Image in WEBP Format
    WEBP,

    /// An Image in PPM Format
    PPM
}

/// The trait that all decoders implement
pub trait ImageDecoder {
    ///Return a tuple containing the width and height of the image
    fn dimensions(&mut self) -> ImageResult<(u32, u32)>;

    ///Return the color type of the image e.g RGB(8) (8bit RGB)
    fn colortype(&mut self) -> ImageResult<ColorType>;

    ///Returns the length in bytes of one decoded row of the image
    fn row_len(&mut self) -> ImageResult<uint>;

    ///Read one row from the image into buf
    ///Returns the row index
    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32>;

    ///Decode the entire image and return it as a Vector
    fn read_image(&mut self) -> ImageResult<Vec<u8>>;

    ///Decode a specific region of the image, represented by the rectangle
    ///starting from ```x``` and ```y``` and having ```length``` and ```width```
    fn load_rect(&mut self, x: u32, y: u32, length: u32, width: u32) -> ImageResult<Vec<u8>> {
        let (w, h) = try!(self.dimensions());

        if length > h || width > w || x > w || y > h {
            return Err(DimensionError)
        }

        let c = try!(self.colortype());

        let bpp = color::bits_per_pixel(c) / 8;

        let rowlen  = try!(self.row_len());

        let mut buf = Vec::from_elem(length as uint * width as uint * bpp, 0u8);
        let mut tmp = Vec::from_elem(rowlen, 0u8);

        loop {
            let row = try!(self.read_scanline(tmp.as_mut_slice()));

            if row - 1 == y {
                break
            }
        }

        for i in range(0, length as uint) {
            {
                let from = tmp.slice_from(x as uint * bpp)
                              .slice_to(width as uint * bpp);

                let to   = buf.mut_slice_from(i * width as uint * bpp)
                              .mut_slice_to(width as uint * bpp);

                slice::bytes::copy_memory(to, from);
            }

            let _ = try!(self.read_scanline(tmp.as_mut_slice()));
        }

        Ok(buf)
    }
}

/// Immutable pixel iterator
pub struct Pixels<'a, I> {
    image:  &'a I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> Iterator<(u32, u32, P)> for Pixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let pixel = self.image.get_pixel(self.x, self.y);
            let p = (self.x, self.y, pixel);

            self.x += 1;

            Some(p)
        }
    }
}

/// Mutable pixel iterator
pub struct MutPixels<'a, I> {
    image:  &'a mut I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> Iterator<(u32, u32, &'a mut P)> for MutPixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, &'a mut P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let tmp = self.image.get_mut_pixel(self.x, self.y);

            //error: lifetime of `self` is too short to guarantee its contents
            //       can be safely reborrowed...
            let ptr = unsafe {
                mem::transmute(tmp)
            };

            let p = (self.x, self.y, ptr);

            self.x += 1;

            Some(p)
        }
    }
}

///A trait for manipulating images.
pub trait GenericImage<P> {
    ///The width and height of this image.
    fn dimensions(&self) -> (u32, u32);

    ///The bounding rectangle of this image.
    fn bounds(&self) -> (u32, u32, u32, u32);

    ///Return the pixel located at (x, y)
    fn get_pixel(&self, x: u32, y: u32) -> P;

    ///Put a pixel at location (x, y)
    fn put_pixel(&mut self, x: u32, y: u32, pixel: P);

    ///Return an Iterator over the pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with their value
    fn pixels(&self) -> Pixels<Self> {
        let (width, height) = self.dimensions();

        Pixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///A trait for images that allow providing mutable references to pixels.
pub trait MutableRefImage<P>: GenericImage<P> {
    ///Return a mutable reference to the pixel located at (x, y)
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P;

    ///Return an Iterator over mutable pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with a mutable reference to them.
    fn mut_pixels(&mut self) -> MutPixels<Self> {
        let (width, height) = self.dimensions();

        MutPixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///An Image whose pixels are contained within a vector
#[deriving(Clone)]
pub struct ImageBuf<P> {
    pixels:  Vec<P>,
    width:   u32,
    height:  u32,
}

impl<T: Primitive, P: Pixel<T>> ImageBuf<P> {
    ///Construct a new ImageBuf with the specified width and height.
    pub fn new(width: u32, height: u32) -> ImageBuf<P> {
        let pixel: P = Default::default();
        let pixels = Vec::from_elem((width * height) as uint, pixel.clone());

        ImageBuf {
            pixels:  pixels,
            width:   width,
            height:  height,
        }
    }

    ///Construct a new ImageBuf by repeated application of the supplied function.
    ///The arguments to the function are the pixel's x and y coordinates.
    pub fn from_fn(width: u32, height: u32, f: | u32, u32 | -> P) -> ImageBuf<P> {
        let pixels = range(0, width).cycle()
                                    .enumerate()
                                    .take(height as uint)
                                    .map( |(y, x)| f(x, y as u32))
                                    .collect();

        ImageBuf::from_pixels(pixels, width, height)
    }

    ///Construct a new ImageBuf from a vector of pixels.
    pub fn from_pixels(pixels: Vec<P>, width: u32, height: u32) -> ImageBuf<P> {
        ImageBuf {
            pixels: pixels,
            width:  width,
            height: height,
        }
    }

    ///Construct a new ImageBuf from a pixel.
    pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuf<P> {
        let buf = Vec::from_elem(width as uint * height as uint, pixel.clone());

        ImageBuf::from_pixels(buf, width, height)
    }

    ///Return an immutable reference to this image's pixel buffer
    pub fn pixelbuf(&self) -> & [P] {
        self.pixels.as_slice()
    }

    ///Return a mutable reference to this image's pixel buffer
    pub fn mut_pixelbuf(&mut self) -> &mut [P] {
        self.pixels.as_mut_slice()
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> GenericImage<P> for ImageBuf<P> {
    fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (0, 0, self.width, self.height)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        let index  = y * self.width + x;

        self.pixels[index as uint]
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        let index  = y * self.width + x;
        let buf    = self.pixels.as_mut_slice();

        buf[index as uint] = pixel;
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> MutableRefImage<P> for ImageBuf<P> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        let index = y * self.width + x;

        self.pixels.get_mut(index as uint)
    }
}

impl<T: Primitive, P: Pixel<T>> Index<(u32, u32), P> for ImageBuf<P> {
    fn index(&self, coords: &(u32, u32)) -> &P {
        let &(x, y) = coords;
        let index  = y * self.width + x;

        &self.pixels[index as uint]
    }
}

/// A View into another image
pub struct SubImage <'a, I> {
    image:   &'a mut I,
    xoffset: u32,
    yoffset: u32,
    xstride: u32,
    ystride: u32,
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> SubImage<'a, I> {
    ///Construct a new subimage
    pub fn new(image: &mut I, x: u32, y: u32, width: u32, height: u32) -> SubImage<I> {
        SubImage {
            image:   image,
            xoffset: x,
            yoffset: y,
            xstride: width,
            ystride: height,
        }
    }

    ///Return a mutable reference to the wrapped image.
    pub fn mut_inner(&mut self) -> &mut I {
        &mut (*self.image)
    }

    ///Change the coordinates of this subimage.
    pub fn change_bounds(&mut self, x: u32, y: u32, width: u32, height: u32) {
        self.xoffset = x;
        self.yoffset = y;
        self.xstride = width;
        self.ystride = height;
    }

    ///Convert this subimage to an ImageBuf
    pub fn to_image(&self) -> ImageBuf<P> {
        let p: P = Default::default();
        let mut out = ImageBuf::from_pixel(self.xstride, self.ystride, p.clone());

        for y in range(0, self.ystride) {
            for x in range(0, self.xstride) {
                let p = self.get_pixel(x, y);
                out.put_pixel(x, y, p);
            }
        }

        out
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> GenericImage<P> for SubImage<'a, I> {
    fn dimensions(&self) -> (u32, u32) {
        (self.xstride, self.ystride)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (self.xoffset, self.yoffset, self.xstride, self.ystride)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        self.image.get_pixel(x + self.xoffset, y + self.yoffset)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        self.image.put_pixel(x + self.xoffset, y + self.yoffset, pixel)
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> MutableRefImage<P> for SubImage<'a, I> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        self.image.get_mut_pixel(x + self.xoffset, y + self.yoffset)
    }
}<commit_msg>Fix error in `ImageBuf::from_fn`. Closes #60<commit_after>use std::mem;
use std::slice;
use std::default::Default;
use std::iter::CloneableIterator;

use color;
use color:: {
    Pixel,
    ColorType
};

/// An enumeration of Image Errors
#[deriving(Show, PartialEq, Eq)]
pub enum ImageError {
    ///The Image is not formatted properly
    FormatError,

    ///The Image's dimensions are either too small or too large
    DimensionError,

    ///The Decoder does not support this image format
    UnsupportedError,

    ///The Decoder does not support this color type
    UnsupportedColor,

    ///Not enough data was provided to the Decoder
    ///to decode the image
    NotEnoughData,

    ///An I/O Error occurred while decoding the image
    IoError,

    ///The end of the image has been reached
    ImageEnd
}

pub type ImageResult<T> = Result<T, ImageError>;

/// An enumeration of supported image formats.
/// Not all formats support both encoding and decoding.
#[deriving(PartialEq, Eq, Show)]
pub enum ImageFormat {
    /// An Image in PNG Format
    PNG,

    /// An Image in JPEG Format
    JPEG,

    /// An Image in GIF Format
    GIF,

    /// An Image in WEBP Format
    WEBP,

    /// An Image in PPM Format
    PPM
}

/// The trait that all decoders implement
pub trait ImageDecoder {
    ///Return a tuple containing the width and height of the image
    fn dimensions(&mut self) -> ImageResult<(u32, u32)>;

    ///Return the color type of the image e.g RGB(8) (8bit RGB)
    fn colortype(&mut self) -> ImageResult<ColorType>;

    ///Returns the length in bytes of one decoded row of the image
    fn row_len(&mut self) -> ImageResult<uint>;

    ///Read one row from the image into buf
    ///Returns the row index
    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32>;

    ///Decode the entire image and return it as a Vector
    fn read_image(&mut self) -> ImageResult<Vec<u8>>;

    ///Decode a specific region of the image, represented by the rectangle
    ///starting from ```x``` and ```y``` and having ```length``` and ```width```
    fn load_rect(&mut self, x: u32, y: u32, length: u32, width: u32) -> ImageResult<Vec<u8>> {
        let (w, h) = try!(self.dimensions());

        if length > h || width > w || x > w || y > h {
            return Err(DimensionError)
        }

        let c = try!(self.colortype());

        let bpp = color::bits_per_pixel(c) / 8;

        let rowlen  = try!(self.row_len());

        let mut buf = Vec::from_elem(length as uint * width as uint * bpp, 0u8);
        let mut tmp = Vec::from_elem(rowlen, 0u8);

        loop {
            let row = try!(self.read_scanline(tmp.as_mut_slice()));

            if row - 1 == y {
                break
            }
        }

        for i in range(0, length as uint) {
            {
                let from = tmp.slice_from(x as uint * bpp)
                              .slice_to(width as uint * bpp);

                let to   = buf.mut_slice_from(i * width as uint * bpp)
                              .mut_slice_to(width as uint * bpp);

                slice::bytes::copy_memory(to, from);
            }

            let _ = try!(self.read_scanline(tmp.as_mut_slice()));
        }

        Ok(buf)
    }
}

/// Immutable pixel iterator
pub struct Pixels<'a, I> {
    image:  &'a I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> Iterator<(u32, u32, P)> for Pixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let pixel = self.image.get_pixel(self.x, self.y);
            let p = (self.x, self.y, pixel);

            self.x += 1;

            Some(p)
        }
    }
}

/// Mutable pixel iterator
pub struct MutPixels<'a, I> {
    image:  &'a mut I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> Iterator<(u32, u32, &'a mut P)> for MutPixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, &'a mut P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let tmp = self.image.get_mut_pixel(self.x, self.y);

            //error: lifetime of `self` is too short to guarantee its contents
            //       can be safely reborrowed...
            let ptr = unsafe {
                mem::transmute(tmp)
            };

            let p = (self.x, self.y, ptr);

            self.x += 1;

            Some(p)
        }
    }
}

///A trait for manipulating images.
pub trait GenericImage<P> {
    ///The width and height of this image.
    fn dimensions(&self) -> (u32, u32);

    ///The bounding rectangle of this image.
    fn bounds(&self) -> (u32, u32, u32, u32);

    ///Return the pixel located at (x, y)
    fn get_pixel(&self, x: u32, y: u32) -> P;

    ///Put a pixel at location (x, y)
    fn put_pixel(&mut self, x: u32, y: u32, pixel: P);

    ///Return an Iterator over the pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with their value
    fn pixels(&self) -> Pixels<Self> {
        let (width, height) = self.dimensions();

        Pixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///A trait for images that allow providing mutable references to pixels.
pub trait MutableRefImage<P>: GenericImage<P> {
    ///Return a mutable reference to the pixel located at (x, y)
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P;

    ///Return an Iterator over mutable pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with a mutable reference to them.
    fn mut_pixels(&mut self) -> MutPixels<Self> {
        let (width, height) = self.dimensions();

        MutPixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///An Image whose pixels are contained within a vector
#[deriving(Clone)]
pub struct ImageBuf<P> {
    pixels:  Vec<P>,
    width:   u32,
    height:  u32,
}

impl<T: Primitive, P: Pixel<T>> ImageBuf<P> {
    ///Construct a new ImageBuf with the specified width and height.
    pub fn new(width: u32, height: u32) -> ImageBuf<P> {
        let pixel: P = Default::default();
        let pixels = Vec::from_elem((width * height) as uint, pixel.clone());

        ImageBuf {
            pixels:  pixels,
            width:   width,
            height:  height,
        }
    }

    ///Construct a new ImageBuf by repeated application of the supplied function.
    ///The arguments to the function are the pixel's x and y coordinates.
    pub fn from_fn(width: u32, height: u32, f: | u32, u32 | -> P) -> ImageBuf<P> {
        let mut pixels: Vec<P> = Vec::with_capacity((width * height) as uint);

        for y in range(0, height) {
            for x in range(0, width) {
                pixels.insert((y * width + x) as uint, f(x, y));
            }
        }

        ImageBuf::from_pixels(pixels, width, height)
    }

    ///Construct a new ImageBuf from a vector of pixels.
    pub fn from_pixels(pixels: Vec<P>, width: u32, height: u32) -> ImageBuf<P> {
        ImageBuf {
            pixels: pixels,
            width:  width,
            height: height,
        }
    }

    ///Construct a new ImageBuf from a pixel.
    pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuf<P> {
        let buf = Vec::from_elem(width as uint * height as uint, pixel.clone());

        ImageBuf::from_pixels(buf, width, height)
    }

    ///Return an immutable reference to this image's pixel buffer
    pub fn pixelbuf(&self) -> & [P] {
        self.pixels.as_slice()
    }

    ///Return a mutable reference to this image's pixel buffer
    pub fn mut_pixelbuf(&mut self) -> &mut [P] {
        self.pixels.as_mut_slice()
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> GenericImage<P> for ImageBuf<P> {
    fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (0, 0, self.width, self.height)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        let index  = y * self.width + x;

        self.pixels[index as uint]
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        let index  = y * self.width + x;
        let buf    = self.pixels.as_mut_slice();

        buf[index as uint] = pixel;
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> MutableRefImage<P> for ImageBuf<P> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        let index = y * self.width + x;

        self.pixels.get_mut(index as uint)
    }
}

impl<T: Primitive, P: Pixel<T>> Index<(u32, u32), P> for ImageBuf<P> {
    fn index(&self, coords: &(u32, u32)) -> &P {
        let &(x, y) = coords;
        let index  = y * self.width + x;

        &self.pixels[index as uint]
    }
}

/// A View into another image
pub struct SubImage <'a, I> {
    image:   &'a mut I,
    xoffset: u32,
    yoffset: u32,
    xstride: u32,
    ystride: u32,
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> SubImage<'a, I> {
    ///Construct a new subimage
    pub fn new(image: &mut I, x: u32, y: u32, width: u32, height: u32) -> SubImage<I> {
        SubImage {
            image:   image,
            xoffset: x,
            yoffset: y,
            xstride: width,
            ystride: height,
        }
    }

    ///Return a mutable reference to the wrapped image.
    pub fn mut_inner(&mut self) -> &mut I {
        &mut (*self.image)
    }

    ///Change the coordinates of this subimage.
    pub fn change_bounds(&mut self, x: u32, y: u32, width: u32, height: u32) {
        self.xoffset = x;
        self.yoffset = y;
        self.xstride = width;
        self.ystride = height;
    }

    ///Convert this subimage to an ImageBuf
    pub fn to_image(&self) -> ImageBuf<P> {
        let p: P = Default::default();
        let mut out = ImageBuf::from_pixel(self.xstride, self.ystride, p.clone());

        for y in range(0, self.ystride) {
            for x in range(0, self.xstride) {
                let p = self.get_pixel(x, y);
                out.put_pixel(x, y, p);
            }
        }

        out
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> GenericImage<P> for SubImage<'a, I> {
    fn dimensions(&self) -> (u32, u32) {
        (self.xstride, self.ystride)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (self.xoffset, self.yoffset, self.xstride, self.ystride)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        self.image.get_pixel(x + self.xoffset, y + self.yoffset)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        self.image.put_pixel(x + self.xoffset, y + self.yoffset, pixel)
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> MutableRefImage<P> for SubImage<'a, I> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        self.image.get_mut_pixel(x + self.xoffset, y + self.yoffset)
    }
}
<|endoftext|>


<commit_before><commit_msg>Started putting together a data structure for tracking currently existing fields<commit_after>

mod PartiallyPersistentExistenceTracker {
  use std::sync::Arc;
  struct Entry <K: Eq> {
    key: K,
    deleted_at: usize,
  }
  //this buffer type has unnecessary indirection, but I was unable to find
  //a library that does the job safely without it.
  //Compare Arc<[Entry<K>]>, which could behave unsafely if I
  //didn't initialize it, but would waste time if I did
  type Buffer <K: Eq> = Arc <Vec<Entry <K>>>;
  struct Inner <K: Eq> {
    buffers: [Buffer; 2],
    revision: usize,
    next_transfer_index: usize,
  }
  pub struct Snapshot <K: Eq> {
    buffer: Buffer,
    used_length: usize,
    revision: usize,
  }
  pub struct Handle <K: Eq> {
    tracker: Arc <Mutex <Inner <K>>,
    key: K,
    possible_indices: [usize; 2],
  }
  pub struct Tracker <K: Eq> {
    inner: Arc <Mutex <Inner <K>>>,
  }

  impl<K: Eq> Inner <K> {
    fn transfer_batch (&mut self ) {

    }
  }

  impl<K: Eq> Tracker <K> {
    pub fn insert (&mut self, key: K)->Handle <K> {

    }
  }
  impl<K: Eq> Drop for Handle <K> {
    fn drop (&mut self) {
      if let tracker = Some (self.tracker.get_mut())
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Add basic Polyphase Filter Bank implementation<commit_after><|endoftext|>


<commit_before><commit_msg>Use keystore::list_accounts instead of addressbook::list<commit_after><|endoftext|>


<commit_before><commit_msg>add fixtures<commit_after>use prolog::ast::*;

use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::collections::btree_map::{IntoIter, IterMut, Values};
use std::mem::swap;
use std::vec::Vec;

pub type OccurrenceSet = BTreeSet<(GenContext, usize)>;

pub struct TempVarData {
    last_term_arity: usize,
    use_set: OccurrenceSet,
    no_use_set: BTreeSet<usize>,
    conflict_set: BTreeSet<usize>
}

// labeled with chunk_num and temp offset (unassigned if 0).
pub enum VarData {
    Perm(usize), Temp(usize, usize, TempVarData)
}

// labeled with chunk numbers.
pub enum VarStatus {
    Perm(usize), Temp(usize, TempVarData) // Perm(chunk_num) | Temp(chunk_num, _)
}

impl VarData {
    pub fn as_reg_type(&self) -> RegType {
        match self {
            &VarData::Temp(_, r, _) => RegType::Temp(r),
            &VarData::Perm(r) => RegType::Perm(r)
        }
    }
}

impl TempVarData {
    fn new(last_term_arity: usize) -> Self {
        TempVarData {
            last_term_arity: last_term_arity,
            use_set: BTreeSet::new(),
            no_use_set: BTreeSet::new(),
            conflict_set: BTreeSet::new()
        }
    }

    fn uses_reg(&self, reg: usize) -> bool {
        for &(_, nreg) in self.use_set.iter() {
            if reg == nreg {
                return true;
            }
        }

        return false;
    }

    fn populate_conflict_set(&mut self) {
        if self.last_term_arity > 0 {
            let arity = self.last_term_arity;
            let mut conflict_set : BTreeSet<usize> = (1..arity).collect();

            for &(_, reg) in self.use_set.iter() {
                conflict_set.remove(&reg);
            }

            self.conflict_set = conflict_set;
        }
    }
}

type VariableFixture<'a>  = (VarStatus, Vec<&'a Cell<VarReg>>);
pub struct VariableFixtures<'a>(BTreeMap<&'a Var, VariableFixture<'a>>);

impl<'a> VariableFixtures<'a>
{
    pub fn new() -> Self {
        VariableFixtures(BTreeMap::new())
    }

    pub fn insert(&mut self, var: &'a Var, vs: VariableFixture<'a>) {
        self.0.insert(var, vs);
    }

    // computes no_use and conflict sets for all temp vars.
    pub fn populate_restricting_sets(&mut self)
    {
        // three stages:
        // 1. move the use sets of each variable to a local HashMap, use_set
        // (iterate mutably, swap mutable refs).
        // 2. drain use_set. For each use set of U, add into the
        // no-use sets of appropriate variables T /= U.
        // 3. Move the use sets back to their original locations in the fixture.
        // Compute the conflict set of u.

        // 1.
        let mut use_sets : HashMap<&'a Var, OccurrenceSet> = HashMap::new();

        for (ref var, &mut (ref mut var_status, _)) in self.iter_mut() {
            if let &mut VarStatus::Temp(_, ref mut var_data) = var_status {
                let mut use_set = OccurrenceSet::new();

                swap(&mut var_data.use_set, &mut use_set);
                use_sets.insert(var, use_set);
            }
        }

        for (u, use_set) in use_sets.drain() {
            // 2.
            for &(term_loc, reg) in use_set.iter() {
                if let GenContext::Last(cn_u) = term_loc {
                    for (ref t, &mut (ref mut var_status, _)) in self.iter_mut() {
                        if let &mut VarStatus::Temp(cn_t, ref mut t_data) = var_status {
                            if cn_u == cn_t && *u != ***t {
                                if !t_data.uses_reg(reg) {
                                    t_data.no_use_set.insert(reg);
                                }
                            }
                        }
                    }
                }
            }

            // 3.
            match self.get_mut(u) {
                Some(&mut (VarStatus::Temp(_, ref mut u_data), _)) => {
                    u_data.use_set = use_set;
                    u_data.populate_conflict_set();
                },
                _ => {}
            };
        }
    }

    fn get_mut(&mut self, u: &'a Var) -> Option<&mut VariableFixture<'a>> {
        self.0.get_mut(u)
    }

    fn iter_mut(&mut self) -> IterMut<&'a Var, VariableFixture<'a>> {
        self.0.iter_mut()
    }

    fn record_temp_info(&mut self,
                        tvd: &mut TempVarData,
                        arg_c: usize,
                        term_loc: GenContext)
    {
        match term_loc {
            GenContext::Head | GenContext::Last(_) => {
                tvd.use_set.insert((term_loc, arg_c));
            },
            _ => {}
        };
    }

    pub fn vars_above_threshold(&self, index: usize) -> usize
    {
        let mut var_count = 0;

        for &(ref var_status, _) in self.values() {
            if let &VarStatus::Perm(i) = var_status {
                if i > index {
                    var_count += 1;
                }
            }
        }

        var_count
    }

    pub fn mark_vars_in_chunk(&mut self,
                              term: &'a Term,
                              last_term_arity: usize,
                              chunk_num: usize,
                              term_loc: GenContext)
    {
        let mut arg_c = 1;

        for term_ref in term.breadth_first_iter() {
            if let TermRef::Var(lvl, cell, var) = term_ref {
                let mut status = self.0.remove(var)
                    .unwrap_or((VarStatus::Temp(chunk_num, TempVarData::new(last_term_arity)),
                                Vec::new()));

                status.1.push(cell);

                match status.0 {
                    VarStatus::Temp(cn, ref mut tvd) if cn == chunk_num => {
                        if let Level::Shallow = lvl {
                            self.record_temp_info(tvd, arg_c, term_loc);
                        }
                    },
                    _ => status.0 = VarStatus::Perm(chunk_num)
                };

                self.0.insert(var, status);
            }

            if let Level::Shallow = term_ref.level() {
                arg_c += 1;
            }
        }
    }

    pub fn into_iter(self) -> IntoIter<&'a Var, VariableFixture<'a>> {
        self.0.into_iter()
    }

    fn values(&self) -> Values<&'a Var, VariableFixture<'a>> {
        self.0.values()
    }

    pub fn set_perm_vals(&self, has_deep_cuts: bool)
    {
        let mut values_vec : Vec<_> = self.values()
            .filter_map(|ref v| {
                match &v.0 {
                    &VarStatus::Perm(i) => Some((i, &v.1)),
                    _ => None
                }
            })
            .collect();

        values_vec.sort_by_key(|ref v| v.0);

        let offset = has_deep_cuts as usize;

        for (i, (_, cells)) in values_vec.into_iter().rev().enumerate() {
            for cell in cells {
                cell.set(VarReg::Norm(RegType::Perm(i + 1 + offset)));
            }
        }
    }

    pub fn mark_unsafe_query_vars(&self, head: &Term, query: &mut CompiledQuery)
    {
        let mut unsafe_vars = HashMap::new();

        for &(_, ref cb) in self.values() {
            if !cb.is_empty() {
                let index = cb.first().unwrap().get().norm();
                unsafe_vars.insert(index, false);
            }
        }

        for term_ref in head.breadth_first_iter() {
            match term_ref {
                TermRef::Var(_, cell, _) => {
                    unsafe_vars.remove(&cell.get().norm());
                },
                _ => {}
            };
        }

        for query_instr in query.iter_mut() {
            match query_instr {
                &mut QueryInstruction::PutValue(RegType::Perm(i), arg) =>
                    if let Some(found) = unsafe_vars.get_mut(&RegType::Perm(i)) {
                        if !*found {
                            *found = true;
                            *query_instr = QueryInstruction::PutUnsafeValue(i, arg);
                        }
                    },
                &mut QueryInstruction::SetVariable(reg)
                    | &mut QueryInstruction::PutVariable(reg, _) =>
                    if let Some(found) = unsafe_vars.get_mut(&reg) {
                        *found = true;
                    },
                &mut QueryInstruction::SetValue(reg) =>
                    if let Some(found) = unsafe_vars.get_mut(&reg) {
                        if !*found {
                            *found = true;
                            *query_instr = QueryInstruction::SetLocalValue(reg);
                        }
                    },
                _ => {}
            };
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Complete problem 5<commit_after>use math::primes;
use std::cmp;
use std::collections::HashMap;

pub fn demo(n: u64) {
    println!("{:?}", lcm(n));
}

fn lcm(n: u64) -> u64 {
    let mut common: HashMap<u64, u64> = HashMap::new();

    for i in 2..n {
        let mut i_primes: HashMap<u64, u64> = HashMap::new();
        for prime in primes::prime_factors(i).into_iter() {
            let count = i_primes.entry(prime).or_insert(0);
            *count += 1;
        }

        for (prime, count) in i_primes.into_iter() {
            let common_count = common.entry(prime).or_insert(count);
            *common_count = cmp::max(common_count.clone(), count);
        }
    }

    common.iter().fold(1, |acc, (prime, count)| {
        use num::traits::ToPrimitive;
        acc * prime.pow(count.clone().to_u32().unwrap())
    })
}
<|endoftext|>


<commit_before><commit_msg>Flatten the public interface for the units/death module<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust small timer interval 333 -> 332 clocks<commit_after><|endoftext|>


<commit_before><commit_msg>add a context creation benchmark<commit_after>#![feature(test)]
extern crate test;
extern crate lwkt;
use lwkt::Context;

static mut ctx_slot: *mut Context = 0 as *mut Context;

#[bench]
fn context_new(b: &mut test::Bencher) {
  b.iter(|| unsafe {
    let mut ctx = Context::new(move || {
      let ctx_ptr = ctx_slot;
      loop {
        (*ctx_ptr).swap()
      }
    });

    ctx_slot = &mut ctx;

    ctx.swap();
  })
}
<|endoftext|>


<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![crate_name = "gfx_macros"]
#![comment = "Helper macros for gfx-rs"]
#![license = "ASL2"]
#![crate_type = "dylib"]

#![feature(macro_rules, plugin_registrar, quote)]

//! Macro extensions crate.
//! Implements `shaders!` macro as well as `#[shader_param]` and
//! `#[vertex_format]` attributes.

extern crate rustc;
extern crate syntax;

use syntax::{ast, attr, ext, codemap};
use syntax::parse::token;

pub mod shader_param;
pub mod vertex_format;

/// Entry point for the plugin phase
#[plugin_registrar]
pub fn registrar(reg: &mut rustc::plugin::Registry) {
    use syntax::parse::token::intern;
    use syntax::ext::base;
    // Register the `#[shader_param]` attribute.
    reg.register_syntax_extension(intern("shader_param"),
        base::ItemDecorator(shader_param::expand));
    // Register the `#[vertex_format]` attribute.
    reg.register_syntax_extension(intern("vertex_format"),
        base::ItemDecorator(vertex_format::expand));
}

/// A hacky thing to get around 'moved value' errors when using `quote_expr!`
/// with `ext::base::ExtCtxt`s.
fn ugh<T, U>(x: &mut T, f: |&mut T| -> U) -> U { f(x) }

/// Scan through the field's attributes and extract the field vertex name. If
/// multiple names are found, use the first name and emit a warning.
fn find_name(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
             attributes: &[ast::Attribute]) -> Option<token::InternedString> {
    attributes.iter().fold(None, |name, attribute| {
        match attribute.node.value.node {
            ast::MetaNameValue(ref attr_name, ref attr_value) => {
                match (attr_name.get(), &attr_value.node) {
                    ("name", &ast::LitStr(ref new_name, _)) => {
                        attr::mark_used(attribute);
                        name.map_or(Some(new_name.clone()), |name| {
                            cx.span_warn(span, format!(
                                "Extra field name detected: {} - \
                                ignoring in favour of: {}", new_name, name
                            ).as_slice());
                            None
                        })
                    }
                    _ => None,
                }
            }
            _ => name,
        }
    })
}

#[macro_export]
macro_rules! shaders {
    (GLSL_120: $v:expr $($t:tt)*) => {
        ::gfx::ShaderSource {
            glsl_120: Some(::gfx::StaticBytes($v)),
            ..shaders!($($t)*)
        }
    };
    (GLSL_150: $v:expr $($t:tt)*) => {
        ::gfx::ShaderSource {
            glsl_150: Some(::gfx::StaticBytes($v)),
            ..shaders!($($t)*)
        }
    };
    () => {
        ::gfx::ShaderSource {
            glsl_120: None,
            glsl_150: None,
        }
    }
}
<commit_msg>Made `shaders!` macro import `gfx` itself<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![crate_name = "gfx_macros"]
#![comment = "Helper macros for gfx-rs"]
#![license = "ASL2"]
#![crate_type = "dylib"]

#![feature(macro_rules, plugin_registrar, quote)]

//! Macro extensions crate.
//! Implements `shaders!` macro as well as `#[shader_param]` and
//! `#[vertex_format]` attributes.

extern crate rustc;
extern crate syntax;

use syntax::{ast, attr, ext, codemap};
use syntax::parse::token;

pub mod shader_param;
pub mod vertex_format;

/// Entry point for the plugin phase
#[plugin_registrar]
pub fn registrar(reg: &mut rustc::plugin::Registry) {
    use syntax::parse::token::intern;
    use syntax::ext::base;
    // Register the `#[shader_param]` attribute.
    reg.register_syntax_extension(intern("shader_param"),
        base::ItemDecorator(shader_param::expand));
    // Register the `#[vertex_format]` attribute.
    reg.register_syntax_extension(intern("vertex_format"),
        base::ItemDecorator(vertex_format::expand));
}

/// A hacky thing to get around 'moved value' errors when using `quote_expr!`
/// with `ext::base::ExtCtxt`s.
fn ugh<T, U>(x: &mut T, f: |&mut T| -> U) -> U { f(x) }

/// Scan through the field's attributes and extract the field vertex name. If
/// multiple names are found, use the first name and emit a warning.
fn find_name(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
             attributes: &[ast::Attribute]) -> Option<token::InternedString> {
    attributes.iter().fold(None, |name, attribute| {
        match attribute.node.value.node {
            ast::MetaNameValue(ref attr_name, ref attr_value) => {
                match (attr_name.get(), &attr_value.node) {
                    ("name", &ast::LitStr(ref new_name, _)) => {
                        attr::mark_used(attribute);
                        name.map_or(Some(new_name.clone()), |name| {
                            cx.span_warn(span, format!(
                                "Extra field name detected: {} - \
                                ignoring in favour of: {}", new_name, name
                            ).as_slice());
                            None
                        })
                    }
                    _ => None,
                }
            }
            _ => name,
        }
    })
}

#[macro_export]
macro_rules! shaders {
    (GLSL_120: $v:expr $($t:tt)*) => {
        {
            mod foo {
                extern crate gfx;
                pub use gfx as g;
            }
            foo::g::ShaderSource {
                glsl_120: Some(::gfx::StaticBytes($v)),
                ..shaders!($($t)*)
            }
        }
    };
    (GLSL_150: $v:expr $($t:tt)*) => {
        {
            mod foo {
                extern crate gfx;
                pub use gfx as g;
            }
            foo::g::ShaderSource {
                glsl_150: Some(::gfx::StaticBytes($v)),
                ..shaders!($($t)*)
            }
        }
    };
    () => {
        {
            mod foo {
                extern crate gfx;
                pub use gfx as g;
            }
            foo::g::ShaderSource {
                glsl_120: None,
                glsl_150: None,
            }
        }
    }
}
<|endoftext|>


<commit_before>#![crate_id(name="tail", vers="1.0.0", author="Morten Olsen Lysgaard")]
/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Morten Olsen Lysgaard <morten@lysgaard.no>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

extern crate getopts;

use std::os;
use std::char;
use std::io::{stdin};
use std::io::BufferedReader;
use std::io::fs::File;
use std::path::Path;
use getopts::{optopt, optflag, getopts, usage};
use std::collections::Deque;
use std::collections::ringbuf::RingBuf;
use std::io::timer::sleep;

static PROGRAM: &'static str = "tail";

#[allow(dead_code)]
fn main () { uumain(os::args()); }

pub fn uumain(args: Vec<String>) {
    let mut line_count = 10u;
    let mut sleep_sec = 1000u64;

    // handle obsolete -number syntax
    let options = match obsolete(args.tail()) {
        (args, Some(n)) => { line_count = n; args },
        (args, None) => args
    };

    let args = options;

    let possible_options = [
        optopt("n", "number", "Number of lines to print", "n"),
        optflag("f", "follow", "Print the file as it grows"),
        optopt("s", "sleep-interval", "Number or seconds to sleep between polling the file when running with -f", "n"),
        optflag("h", "help", "help"),
        optflag("V", "version", "version"),
    ];

    let given_options = match getopts(args.as_slice(), possible_options) {
        Ok (m) => { m }
        Err(_) => {
            println!("{:s}", usage(PROGRAM, possible_options));
            return
        }
    };

    if given_options.opt_present("h") {
        println!("{:s}", usage(PROGRAM, possible_options));
        return;
    }
    if given_options.opt_present("V") { version(); return }

    let follow = given_options.opt_present("f");
    if follow {
        match given_options.opt_str("s") {
            Some(n) => {
                let parsed : Option<u64> = from_str(n.as_slice());
                match parsed {
                    Some(m) => { sleep_sec = m*1000 }
                    None => {}
                }
            }
            None => {}
        };
    }

    match given_options.opt_str("n") {
        Some(n) => {
            match from_str(n.as_slice()) {
                Some(m) => { line_count = m }
                None => {}
            }
        }
        None => {}
    };

    let files = given_options.free;

    if files.is_empty() {
        let mut buffer = BufferedReader::new(stdin());
        tail(&mut buffer, line_count, follow, sleep_sec);
    } else {
        let mut multiple = false;
        let mut firstime = true;

        if files.len() > 1 {
            multiple = true;
        }

        for file in files.iter() {
            if multiple {
                if !firstime { println!(""); }
                println!("==> {:s} <==", file.as_slice());
            }
            firstime = false;

            let path = Path::new(file.as_slice());
            let reader = File::open(&path).unwrap();
            let mut buffer = BufferedReader::new(reader);
            tail(&mut buffer, line_count, follow, sleep_sec);
        }
    }
}

// It searches for an option in the form of -123123
//
// In case is found, the options vector will get rid of that object so that
// getopts works correctly.
fn obsolete (options: &[String]) -> (Vec<String>, Option<uint>) {
    let mut options: Vec<String> = Vec::from_slice(options);
    let mut a = 0;
    let b = options.len();

    while a < b {
        let current = options.get(a).clone();
        let current = current.as_slice();

        if current.len() > 1 && current[0] == '-' as u8 {
            let len = current.len();
            for pos in range(1, len) {
                // Ensure that the argument is only made out of digits
                if !char::is_digit(current.char_at(pos)) { break; }

                // If this is the last number
                if pos == len - 1 {
                    options.remove(a);
                    let number : Option<uint> = from_str(current.slice(1,len));
                    return (options, Some(number.unwrap()));
                }
            }
        }

        a += 1;
    };

    (options, None)
}

fn tail<T: Reader> (reader: &mut BufferedReader<T>, line_count:uint, follow:bool, sleep_sec:u64) {
    // read trough each line and store them in a ringbuffer that always contains
    // line_count lines. When reaching the end of file, output the lines in the
    // ringbuf.
    let mut ringbuf : RingBuf<String> = RingBuf::new();
    for io_line in reader.lines(){
        match io_line {
            Ok(line) => {
                if line_count<=ringbuf.len(){
                  ringbuf.pop_front();
                }
                ringbuf.push_back(line);
            }
            Err(err) => fail!(err)
        }
    }
    for line in ringbuf.iter() {
        print!("{}", line);
    }

    // if we follow the file, sleep a bit and print the rest if the file has grown.
    while follow {
        sleep(sleep_sec);
        for io_line in reader.lines() {
            match io_line {
                Ok(line) => print!("{}", line),
                Err(err) => fail!(err)
            }
        }
    }
}

fn version () {
    println!("tail version 0.0.1");
}
<commit_msg>tail: fix typo<commit_after>#![crate_id(name="tail", vers="1.0.0", author="Morten Olsen Lysgaard")]
/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Morten Olsen Lysgaard <morten@lysgaard.no>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

extern crate getopts;

use std::os;
use std::char;
use std::io::{stdin};
use std::io::BufferedReader;
use std::io::fs::File;
use std::path::Path;
use getopts::{optopt, optflag, getopts, usage};
use std::collections::Deque;
use std::collections::ringbuf::RingBuf;
use std::io::timer::sleep;

static PROGRAM: &'static str = "tail";

#[allow(dead_code)]
fn main () { uumain(os::args()); }

pub fn uumain(args: Vec<String>) {
    let mut line_count = 10u;
    let mut sleep_sec = 1000u64;

    // handle obsolete -number syntax
    let options = match obsolete(args.tail()) {
        (args, Some(n)) => { line_count = n; args },
        (args, None) => args
    };

    let args = options;

    let possible_options = [
        optopt("n", "number", "Number of lines to print", "n"),
        optflag("f", "follow", "Print the file as it grows"),
        optopt("s", "sleep-interval", "Number or seconds to sleep between polling the file when running with -f", "n"),
        optflag("h", "help", "help"),
        optflag("V", "version", "version"),
    ];

    let given_options = match getopts(args.as_slice(), possible_options) {
        Ok (m) => { m }
        Err(_) => {
            println!("{:s}", usage(PROGRAM, possible_options));
            return
        }
    };

    if given_options.opt_present("h") {
        println!("{:s}", usage(PROGRAM, possible_options));
        return;
    }
    if given_options.opt_present("V") { version(); return }

    let follow = given_options.opt_present("f");
    if follow {
        match given_options.opt_str("s") {
            Some(n) => {
                let parsed : Option<u64> = from_str(n.as_slice());
                match parsed {
                    Some(m) => { sleep_sec = m*1000 }
                    None => {}
                }
            }
            None => {}
        };
    }

    match given_options.opt_str("n") {
        Some(n) => {
            match from_str(n.as_slice()) {
                Some(m) => { line_count = m }
                None => {}
            }
        }
        None => {}
    };

    let files = given_options.free;

    if files.is_empty() {
        let mut buffer = BufferedReader::new(stdin());
        tail(&mut buffer, line_count, follow, sleep_sec);
    } else {
        let mut multiple = false;
        let mut firstime = true;

        if files.len() > 1 {
            multiple = true;
        }

        for file in files.iter() {
            if multiple {
                if !firstime { println!(""); }
                println!("==> {:s} <==", file.as_slice());
            }
            firstime = false;

            let path = Path::new(file.as_slice());
            let reader = File::open(&path).unwrap();
            let mut buffer = BufferedReader::new(reader);
            tail(&mut buffer, line_count, follow, sleep_sec);
        }
    }
}

// It searches for an option in the form of -123123
//
// In case is found, the options vector will get rid of that object so that
// getopts works correctly.
fn obsolete (options: &[String]) -> (Vec<String>, Option<uint>) {
    let mut options: Vec<String> = Vec::from_slice(options);
    let mut a = 0;
    let b = options.len();

    while a < b {
        let current = options.get(a).clone();
        let current = current.as_slice();

        if current.len() > 1 && current[0] == '-' as u8 {
            let len = current.len();
            for pos in range(1, len) {
                // Ensure that the argument is only made out of digits
                if !char::is_digit(current.char_at(pos)) { break; }

                // If this is the last number
                if pos == len - 1 {
                    options.remove(a);
                    let number : Option<uint> = from_str(current.slice(1,len));
                    return (options, Some(number.unwrap()));
                }
            }
        }

        a += 1;
    };

    (options, None)
}

fn tail<T: Reader> (reader: &mut BufferedReader<T>, line_count:uint, follow:bool, sleep_sec:u64) {
    // read through each line and store them in a ringbuffer that always contains
    // line_count lines. When reaching the end of file, output the lines in the
    // ringbuf.
    let mut ringbuf : RingBuf<String> = RingBuf::new();
    for io_line in reader.lines(){
        match io_line {
            Ok(line) => {
                if line_count<=ringbuf.len(){
                  ringbuf.pop_front();
                }
                ringbuf.push_back(line);
            }
            Err(err) => fail!(err)
        }
    }
    for line in ringbuf.iter() {
        print!("{}", line);
    }

    // if we follow the file, sleep a bit and print the rest if the file has grown.
    while follow {
        sleep(sleep_sec);
        for io_line in reader.lines() {
            match io_line {
                Ok(line) => print!("{}", line),
                Err(err) => fail!(err)
            }
        }
    }
}

fn version () {
    println!("tail version 0.0.1");
}
<|endoftext|>


<commit_before><commit_msg>update code for chapter 8<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #9515 : pnkfelix/rust/fsk-test-for-issue-5153, r=alexcrichton<commit_after>// Copyright 2013 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.

// error-pattern: type `@Foo:'static` does not implement any method in scope named `foo`

trait Foo {
    fn foo(~self);
}

impl Foo for int {
    fn foo(~self) { }
}

fn main() {
    (@5 as @Foo).foo();
}
<|endoftext|>


<commit_before><commit_msg>Finish panic handler tests<commit_after>#![feature(panic_info_message)]

use core::fmt::{self, Write};
use daedalos::qemu::{exit_qemu, QemuExitCode};
use daedalos::{sprint, sprintln};

const MESSAGE: &str = "Example panic message from panic_handler test";
const PANIC_LINE: u32 = 14; // adjust this when moving the `panic!` call

#[no_mangle]
pub extern "C" fn _start() -> ! {
    sprint!("panic_handler... ");
    panic!(MESSAGE); // must be in line `PANIC_LINE`
}

fn check_message(info: &PanicInfo) {
    let message = info.message().unwrap_or_else(|| fail("no message"));
    let mut compare_message = CompareMessage { expected: MESSAGE };
    write!(&mut compare_message, "{}", message).unwrap_or_else(|_| fail("write failed"));
    if !compare_message.expected.is_empty() {
        fail("message shorter than expected message");
    }
}

/// Compares a `fmt::Arguments` instance with the `MESSAGE` string
///
/// To use this type, write the `fmt::Arguments` instance to it using the
/// `write` macro. If the message component matches `MESSAGE`, the `expected`
/// field is the empty string.
struct CompareMessage {
    expected: &'static str,
}

impl fmt::Write for CompareMessage {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        if self.expected.starts_with(s) {
            self.expected = &self.expected[s.len()..];
        } else {
            fail("message not equal to expected message");
        }
        Ok(())
    }
}

fn fail(error: &str) -> ! {
    serial_println!("[failed]");
    serial_println!("{}", error);
    exit_qemu(QemuExitCode::Failed);
    loop {}
}

fn check_location(info: &PanicInfo) {
    let location = info.location().unwrap_or_else(|| fail("no location"));
    if location.file() != file!() {
        fail("file name wrong");
    }
    if location.line() != PANIC_LINE {
        fail("file line wrong");
    }
}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    check_message(info);
    check_location(info);
    serial_println!("[ok]");
    exit_qemu(QemuExitCode::Success);
    loop {}
}
<|endoftext|>


<commit_before><commit_msg>Fix margins<commit_after><|endoftext|>


<commit_before><commit_msg>returning the ownership<commit_after><|endoftext|>


<commit_before>use std::fs::{self, File, OpenOptions};
use std::io::*;
use std::io;
use std::path::{Path, PathBuf, Display};

use term::color::CYAN;
use fs2::{FileExt, lock_contended_error};
#[allow(unused_imports)]
use libc;

use util::{CargoResult, ChainError, Config, human};

pub struct FileLock {
    f: Option<File>,
    path: PathBuf,
    state: State,
}

#[derive(PartialEq)]
enum State {
    Unlocked,
    Shared,
    Exclusive,
}

impl FileLock {
    /// Returns the underlying file handle of this lock.
    pub fn file(&self) -> &File {
        self.f.as_ref().unwrap()
    }

    /// Returns the underlying path that this lock points to.
    ///
    /// Note that special care must be taken to ensure that the path is not
    /// referenced outside the lifetime of this lock.
    pub fn path(&self) -> &Path {
        assert!(self.state != State::Unlocked);
        &self.path
    }

    /// Returns the parent path containing this file
    pub fn parent(&self) -> &Path {
        assert!(self.state != State::Unlocked);
        self.path.parent().unwrap()
    }

    /// Removes all sibling files to this locked file.
    ///
    /// This can be useful if a directory is locked with a sentinel file but it
    /// needs to be cleared out as it may be corrupt.
    pub fn remove_siblings(&self) -> io::Result<()> {
        let path = self.path();
        for entry in path.parent().unwrap().read_dir()? {
            let entry = entry?;
            if Some(&entry.file_name()[..]) == path.file_name() {
                continue
            }
            let kind = entry.file_type()?;
            if kind.is_dir() {
                fs::remove_dir_all(entry.path())?;
            } else {
                fs::remove_file(entry.path())?;
            }
        }
        Ok(())
    }
}

impl Read for FileLock {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.file().read(buf)
    }
}

impl Seek for FileLock {
    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
        self.file().seek(to)
    }
}

impl Write for FileLock {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file().write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file().flush()
    }
}

impl Drop for FileLock {
    fn drop(&mut self) {
        if self.state != State::Unlocked {
            if let Some(f) = self.f.take() {
                let _ = f.unlock();
            }
        }
    }
}

/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
    root: PathBuf,
}

impl Filesystem {
    /// Creates a new filesystem to be rooted at the given path.
    pub fn new(path: PathBuf) -> Filesystem {
        Filesystem { root: path }
    }

    /// Like `Path::join`, creates a new filesystem rooted at this filesystem
    /// joined with the given path.
    pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
        Filesystem::new(self.root.join(other))
    }

    /// Like `Path::push`, pushes a new path component onto this filesystem.
    pub fn push<T: AsRef<Path>>(&mut self, other: T) {
        self.root.push(other);
    }

    /// Consumes this filesystem and returns the underlying `PathBuf`.
    ///
    /// Note that this is a relatively dangerous operation and should be used
    /// with great caution!.
    pub fn into_path_unlocked(self) -> PathBuf {
        self.root
    }

    /// Creates the directory pointed to by this filesystem.
    ///
    /// Handles errors where other Cargo processes are also attempting to
    /// concurrently create this directory.
    pub fn create_dir(&self) -> io::Result<()> {
        return create_dir_all(&self.root);
    }

    /// Returns an adaptor that can be used to print the path of this
    /// filesystem.
    pub fn display(&self) -> Display {
        self.root.display()
    }

    /// Opens exclusive access to a file, returning the locked version of a
    /// file.
    ///
    /// This function will create a file at `path` if it doesn't already exist
    /// (including intermediate directories), and then it will acquire an
    /// exclusive lock on `path`. If the process must block waiting for the
    /// lock, the `msg` is printed to `config`.
    ///
    /// The returned file can be accessed to look at the path and also has
    /// read/write access to the underlying file.
    pub fn open_rw<P>(&self,
                      path: P,
                      config: &Config,
                      msg: &str) -> CargoResult<FileLock>
        where P: AsRef<Path>
    {
        self.open(path.as_ref(),
                  OpenOptions::new().read(true).write(true).create(true),
                  State::Exclusive,
                  config,
                  msg)
    }

    /// Opens shared access to a file, returning the locked version of a file.
    ///
    /// This function will fail if `path` doesn't already exist, but if it does
    /// then it will acquire a shared lock on `path`. If the process must block
    /// waiting for the lock, the `msg` is printed to `config`.
    ///
    /// The returned file can be accessed to look at the path and also has read
    /// access to the underlying file. Any writes to the file will return an
    /// error.
    pub fn open_ro<P>(&self,
                      path: P,
                      config: &Config,
                      msg: &str) -> CargoResult<FileLock>
        where P: AsRef<Path>
    {
        self.open(path.as_ref(),
                  OpenOptions::new().read(true),
                  State::Shared,
                  config,
                  msg)
    }

    fn open(&self,
            path: &Path,
            opts: &OpenOptions,
            state: State,
            config: &Config,
            msg: &str) -> CargoResult<FileLock> {
        let path = self.root.join(path);

        // If we want an exclusive lock then if we fail because of NotFound it's
        // likely because an intermediate directory didn't exist, so try to
        // create the directory and then continue.
        let f = opts.open(&path).or_else(|e| {
            if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
                create_dir_all(path.parent().unwrap())?;
                opts.open(&path)
            } else {
                Err(e)
            }
        }).chain_error(|| {
            human(format!("failed to open: {}", path.display()))
        })?;
        match state {
            State::Exclusive => {
                acquire(config, msg, &path,
                        &|| f.try_lock_exclusive(),
                        &|| f.lock_exclusive())?;
            }
            State::Shared => {
                acquire(config, msg, &path,
                        &|| f.try_lock_shared(),
                        &|| f.lock_shared())?;
            }
            State::Unlocked => {}

        }
        Ok(FileLock { f: Some(f), path: path, state: state })
    }
}

/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(config: &Config,
           msg: &str,
           path: &Path,
           try: &Fn() -> io::Result<()>,
           block: &Fn() -> io::Result<()>) -> CargoResult<()> {

    // File locking on Unix is currently implemented via `flock`, which is known
    // to be broken on NFS. We could in theory just ignore errors that happen on
    // NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
    // forever**, even if the nonblocking flag is passed!
    //
    // As a result, we just skip all file locks entirely on NFS mounts. That
    // should avoid calling any `flock` functions at all, and it wouldn't work
    // there anyway.
    //
    // [1]: https://github.com/rust-lang/cargo/issues/2615
    if is_on_nfs_mount(path) {
        return Ok(())
    }

    match try() {
        Ok(()) => return Ok(()),

        // Like above, where we ignore file locking on NFS mounts on Linux, we
        // do the same on OSX here. Note that ENOTSUP is an OSX_specific
        // constant.
        #[cfg(target_os = "macos")]
        Err(ref e) if e.raw_os_error() == Some(libc::ENOTSUP) => return Ok(()),

        Err(e) => {
            if e.raw_os_error() != lock_contended_error().raw_os_error() {
                return Err(human(e)).chain_error(|| {
                    human(format!("failed to lock file: {}", path.display()))
                })
            }
        }
    }
    let msg = format!("waiting for file lock on {}", msg);
    config.shell().err().say_status("Blocking", &msg, CYAN, true)?;

    return block().chain_error(|| {
        human(format!("failed to lock file: {}", path.display()))
    });

    #[cfg(all(target_os = "linux", not(target_env = "musl")))]
    fn is_on_nfs_mount(path: &Path) -> bool {
        use std::ffi::CString;
        use std::mem;
        use std::os::unix::prelude::*;

        let path = match CString::new(path.as_os_str().as_bytes()) {
            Ok(path) => path,
            Err(_) => return false,
        };

        unsafe {
            let mut buf: libc::statfs = mem::zeroed();
            let r = libc::statfs(path.as_ptr(), &mut buf);

            r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
        }
    }

    #[cfg(any(not(target_os = "linux"), target_env = "musl"))]
    fn is_on_nfs_mount(_path: &Path) -> bool {
        false
    }
}

fn create_dir_all(path: &Path) -> io::Result<()> {
    match create_dir(path) {
        Ok(()) => return Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::NotFound {
                if let Some(p) = path.parent() {
                    return create_dir_all(p).and_then(|()| create_dir(path))
                }
            }
            Err(e)
        }
    }
}

fn create_dir(path: &Path) -> io::Result<()> {
    match fs::create_dir(path) {
        Ok(()) => Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
        Err(e) => Err(e),
    }
}
<commit_msg>trying to fix unimplemented flock under linux<commit_after>use std::fs::{self, File, OpenOptions};
use std::io::*;
use std::io;
use std::path::{Path, PathBuf, Display};

use term::color::CYAN;
use fs2::{FileExt, lock_contended_error};
#[allow(unused_imports)]
use libc;

use util::{CargoResult, ChainError, Config, human};

pub struct FileLock {
    f: Option<File>,
    path: PathBuf,
    state: State,
}

#[derive(PartialEq)]
enum State {
    Unlocked,
    Shared,
    Exclusive,
}

impl FileLock {
    /// Returns the underlying file handle of this lock.
    pub fn file(&self) -> &File {
        self.f.as_ref().unwrap()
    }

    /// Returns the underlying path that this lock points to.
    ///
    /// Note that special care must be taken to ensure that the path is not
    /// referenced outside the lifetime of this lock.
    pub fn path(&self) -> &Path {
        assert!(self.state != State::Unlocked);
        &self.path
    }

    /// Returns the parent path containing this file
    pub fn parent(&self) -> &Path {
        assert!(self.state != State::Unlocked);
        self.path.parent().unwrap()
    }

    /// Removes all sibling files to this locked file.
    ///
    /// This can be useful if a directory is locked with a sentinel file but it
    /// needs to be cleared out as it may be corrupt.
    pub fn remove_siblings(&self) -> io::Result<()> {
        let path = self.path();
        for entry in path.parent().unwrap().read_dir()? {
            let entry = entry?;
            if Some(&entry.file_name()[..]) == path.file_name() {
                continue
            }
            let kind = entry.file_type()?;
            if kind.is_dir() {
                fs::remove_dir_all(entry.path())?;
            } else {
                fs::remove_file(entry.path())?;
            }
        }
        Ok(())
    }
}

impl Read for FileLock {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.file().read(buf)
    }
}

impl Seek for FileLock {
    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
        self.file().seek(to)
    }
}

impl Write for FileLock {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file().write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file().flush()
    }
}

impl Drop for FileLock {
    fn drop(&mut self) {
        if self.state != State::Unlocked {
            if let Some(f) = self.f.take() {
                let _ = f.unlock();
            }
        }
    }
}

/// A "filesystem" is intended to be a globally shared, hence locked, resource
/// in Cargo.
///
/// The `Path` of a filesystem cannot be learned unless it's done in a locked
/// fashion, and otherwise functions on this structure are prepared to handle
/// concurrent invocations across multiple instances of Cargo.
#[derive(Clone, Debug)]
pub struct Filesystem {
    root: PathBuf,
}

impl Filesystem {
    /// Creates a new filesystem to be rooted at the given path.
    pub fn new(path: PathBuf) -> Filesystem {
        Filesystem { root: path }
    }

    /// Like `Path::join`, creates a new filesystem rooted at this filesystem
    /// joined with the given path.
    pub fn join<T: AsRef<Path>>(&self, other: T) -> Filesystem {
        Filesystem::new(self.root.join(other))
    }

    /// Like `Path::push`, pushes a new path component onto this filesystem.
    pub fn push<T: AsRef<Path>>(&mut self, other: T) {
        self.root.push(other);
    }

    /// Consumes this filesystem and returns the underlying `PathBuf`.
    ///
    /// Note that this is a relatively dangerous operation and should be used
    /// with great caution!.
    pub fn into_path_unlocked(self) -> PathBuf {
        self.root
    }

    /// Creates the directory pointed to by this filesystem.
    ///
    /// Handles errors where other Cargo processes are also attempting to
    /// concurrently create this directory.
    pub fn create_dir(&self) -> io::Result<()> {
        return create_dir_all(&self.root);
    }

    /// Returns an adaptor that can be used to print the path of this
    /// filesystem.
    pub fn display(&self) -> Display {
        self.root.display()
    }

    /// Opens exclusive access to a file, returning the locked version of a
    /// file.
    ///
    /// This function will create a file at `path` if it doesn't already exist
    /// (including intermediate directories), and then it will acquire an
    /// exclusive lock on `path`. If the process must block waiting for the
    /// lock, the `msg` is printed to `config`.
    ///
    /// The returned file can be accessed to look at the path and also has
    /// read/write access to the underlying file.
    pub fn open_rw<P>(&self,
                      path: P,
                      config: &Config,
                      msg: &str) -> CargoResult<FileLock>
        where P: AsRef<Path>
    {
        self.open(path.as_ref(),
                  OpenOptions::new().read(true).write(true).create(true),
                  State::Exclusive,
                  config,
                  msg)
    }

    /// Opens shared access to a file, returning the locked version of a file.
    ///
    /// This function will fail if `path` doesn't already exist, but if it does
    /// then it will acquire a shared lock on `path`. If the process must block
    /// waiting for the lock, the `msg` is printed to `config`.
    ///
    /// The returned file can be accessed to look at the path and also has read
    /// access to the underlying file. Any writes to the file will return an
    /// error.
    pub fn open_ro<P>(&self,
                      path: P,
                      config: &Config,
                      msg: &str) -> CargoResult<FileLock>
        where P: AsRef<Path>
    {
        self.open(path.as_ref(),
                  OpenOptions::new().read(true),
                  State::Shared,
                  config,
                  msg)
    }

    fn open(&self,
            path: &Path,
            opts: &OpenOptions,
            state: State,
            config: &Config,
            msg: &str) -> CargoResult<FileLock> {
        let path = self.root.join(path);

        // If we want an exclusive lock then if we fail because of NotFound it's
        // likely because an intermediate directory didn't exist, so try to
        // create the directory and then continue.
        let f = opts.open(&path).or_else(|e| {
            if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
                create_dir_all(path.parent().unwrap())?;
                opts.open(&path)
            } else {
                Err(e)
            }
        }).chain_error(|| {
            human(format!("failed to open: {}", path.display()))
        })?;
        match state {
            State::Exclusive => {
                acquire(config, msg, &path,
                        &|| f.try_lock_exclusive(),
                        &|| f.lock_exclusive())?;
            }
            State::Shared => {
                acquire(config, msg, &path,
                        &|| f.try_lock_shared(),
                        &|| f.lock_shared())?;
            }
            State::Unlocked => {}

        }
        Ok(FileLock { f: Some(f), path: path, state: state })
    }
}

/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(config: &Config,
           msg: &str,
           path: &Path,
           try: &Fn() -> io::Result<()>,
           block: &Fn() -> io::Result<()>) -> CargoResult<()> {

    // File locking on Unix is currently implemented via `flock`, which is known
    // to be broken on NFS. We could in theory just ignore errors that happen on
    // NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
    // forever**, even if the nonblocking flag is passed!
    //
    // As a result, we just skip all file locks entirely on NFS mounts. That
    // should avoid calling any `flock` functions at all, and it wouldn't work
    // there anyway.
    //
    // [1]: https://github.com/rust-lang/cargo/issues/2615
    if is_on_nfs_mount(path) {
        return Ok(())
    }

    match try() {
        Ok(()) => return Ok(()),

        // Like above, where we ignore file locking on NFS mounts on Linux, we
        // do the same on OSX here. Note that ENOTSUP is an OSX_specific
        // constant.
        #[cfg(target_os = "macos")]
        Err(ref e) if e.raw_os_error() == Some(libc::ENOTSUP) => return Ok(()),

        #[cfg(target_os = "linux")]
        Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => return Ok(()),

        Err(e) => {
            if e.raw_os_error() != lock_contended_error().raw_os_error() {
                return Err(human(e)).chain_error(|| {
                    human(format!("failed to lock file: {}", path.display()))
                })
            }
        }
    }
    let msg = format!("waiting for file lock on {}", msg);
    config.shell().err().say_status("Blocking", &msg, CYAN, true)?;

    return block().chain_error(|| {
        human(format!("failed to lock file: {}", path.display()))
    });

    #[cfg(all(target_os = "linux", not(target_env = "musl")))]
    fn is_on_nfs_mount(path: &Path) -> bool {
        use std::ffi::CString;
        use std::mem;
        use std::os::unix::prelude::*;

        let path = match CString::new(path.as_os_str().as_bytes()) {
            Ok(path) => path,
            Err(_) => return false,
        };

        unsafe {
            let mut buf: libc::statfs = mem::zeroed();
            let r = libc::statfs(path.as_ptr(), &mut buf);

            r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
        }
    }

    #[cfg(any(not(target_os = "linux"), target_env = "musl"))]
    fn is_on_nfs_mount(_path: &Path) -> bool {
        false
    }
}

fn create_dir_all(path: &Path) -> io::Result<()> {
    match create_dir(path) {
        Ok(()) => return Ok(()),
        Err(e) => {
            if e.kind() == io::ErrorKind::NotFound {
                if let Some(p) = path.parent() {
                    return create_dir_all(p).and_then(|()| create_dir(path))
                }
            }
            Err(e)
        }
    }
}

fn create_dir(path: &Path) -> io::Result<()> {
    match fs::create_dir(path) {
        Ok(()) => Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
        Err(e) => Err(e),
    }
}
<|endoftext|>


<commit_before><commit_msg>Added a modulation example and tested results with the Keysight 89600 VSA software<commit_after>extern crate basic_dsp;
use basic_dsp::*;
use basic_dsp::conv_types::*;

use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::f64::consts::PI;

fn main() {
    let number_of_symbols = 10000;
    let mut prbs = Prbs15::new();
    let mut channel1 = RealTimeVector64::from_constant(0.0, number_of_symbols);
    let mut channel2 = RealTimeVector64::from_constant(0.0, number_of_symbols);
    let mut empty = ComplexTimeVector64::empty();

    for i in 0..3 {
        fill_vectors_with_prbs(&mut channel1, &mut channel2, &mut prbs);
        let complex =
            empty.set_real_imag(&channel1, &channel2)
            .and_then(|v| v.interpolatei(&RaisedCosineFunction::new(0.35), 10))
            .expect("Complex baseband vector from real vectors");
        let mut file = File::create(format!("baseband_time{}.csv", i)).expect("Failed to create baseband time file");
        complex_vector_to_file(&complex, &mut file).expect("Failed to write baseband time file");

        let modulated =
            complex.multiply_complex_exponential(0.25 * PI, 0.0)
            .expect("frequency shift");

        let real =
            modulated.to_real()
            .expect("Mod to real");

        let mut file = File::create(format!("modulated_time{}.csv", i)).expect("Failed to create modulated time file");
        real_vector_to_file(&real, &mut file).expect("Failed to write modulated time file");

        let delta = real.delta();
        empty = real.rededicate_as_complex_time_vector(delta); // Reuse memory
    }
}

struct Prbs15 {
    lfsr: u32
}

impl Prbs15 {
    fn new() -> Self {
        Prbs15 { lfsr: 0x1 }
    }

    fn next(&mut self) -> f64 {
        let bit = (self.lfsr ^ self.lfsr >> 14) & 0x1;
        self.lfsr = (self.lfsr >> 1) | (bit << 14);
        (bit as f64 - 0.5)
    }
}

fn fill_vectors_with_prbs(
    channel1: &mut RealTimeVector64,
    channel2: &mut RealTimeVector64,
    prbs: &mut Prbs15) {
    assert!(channel1.points() == channel2.points());
    for i in 0..channel1.points() {
        channel2[i] = prbs.next();
        channel1[i] = prbs.next();
    }
}

fn complex_vector_to_file(vector: &ComplexTimeVector64, f: &mut File) -> io::Result <()>  {
    let mut i = 0;
    while i < vector.len() {
        try! { writeln!(f, "{}, {}", vector[i], vector[i + 1]) };
        i += 2;
    }
    Ok(())
}

fn real_vector_to_file(vector: &RealTimeVector64, f: &mut File) -> io::Result <()>  {
    let mut i = 0;
    while i < vector.len() {
        try! { writeln!(f, "{}", vector[i]) };
        i += 2;
    }
    Ok(())
}<|endoftext|>


<commit_before>/// Implements the [`Identifiable`][identifiable] trait for a given struct. This
/// macro should be called by copy/pasting the definition of the struct into it.
///
/// The struct must have a field called `id`, and the type of that field must be
/// `Copy`. This macro does not work with tuple structs.
///
/// [identifiable]: query_source/trait.Identifiable.html
///
/// # Example
///
/// ```no_run
/// # #[macro_use] extern crate diesel;
/// struct User {
///     id: i32,
///     name: String,
/// }
///
/// Identifiable! {
///     struct User {
///         id: i32,
///         name: String,
///     }
/// }
/// # fn main() {}
/// ```
///
/// To avoid copying your struct definition, you can use the
/// [custom_derive crate][custom_derive].
///
/// [custom_derive]: https://crates.io/crates/custom_derive
///
/// ```ignore
/// custom_derive! {
///     #[derive(Identifiable)]
///     struct User {
///         id: i32,
///         name: String,
///     }
/// }
/// ```
macro_rules! Identifiable {
    // Strip empty argument list if given (Passed by custom_derive macro)
    (() $($body:tt)*) => {
        Identifiable! {
            $($body)*
        }
    };

    // Strip meta items, pub (if present) and struct from definition
    (
        $(#[$ignore:meta])*
        $(pub)* struct $($body:tt)*
    ) => {
        Identifiable! {
            $($body)*
        }
    };

    // We found the `id` field, return the final impl
    (
        (
            struct_ty = $struct_ty:ty,
        ),
        fields = [{
            field_name: id,
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        } $($fields:tt)*],
    ) => {
        impl $crate::associations::Identifiable for $struct_ty {
            type Id = $field_ty;

            fn id(&self) -> Self::Id {
                self.id
            }
        }
    };

    // Search for the `id` field and continue
    (
        (
            struct_ty = $struct_ty:ty,
        ),
        fields = [{
            field_name: $field_name:ident,
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        } $($fields:tt)*],
    ) => {
        Identifiable! {
            (struct_ty = $struct_ty,),
            fields = [$($fields)*],
        }
    };

    // Handle struct with no generics
    (
        $struct_name:ident
        $body:tt $(;)*
    ) => {
        __diesel_parse_struct_body! {
            (
                struct_ty = $struct_name,
            ),
            callback = Identifiable,
            body = $body,
        }
    };
}

#[test]
fn derive_identifiable_on_simple_struct() {
    use associations::Identifiable;

    struct Foo {
        id: i32,
        #[allow(dead_code)]
        foo: i32,
    }

    Identifiable! {
        struct Foo {
            id: i32,
            foo: i32,
        }
    }

    let foo1 = Foo { id: 1, foo: 2 };
    let foo2 = Foo { id: 2, foo: 3 };
    assert_eq!(1, foo1.id());
    assert_eq!(2, foo2.id());
}

#[test]
fn derive_identifiable_when_id_is_not_first_field() {
    use associations::Identifiable;

    struct Foo {
        #[allow(dead_code)]
        foo: i32,
        id: i32,
    }

    Identifiable! {
        struct Foo {
            foo: i32,
            id: i32,
        }
    }

    let foo1 = Foo { id: 1, foo: 2 };
    let foo2 = Foo { id: 2, foo: 3 };
    assert_eq!(1, foo1.id());
    assert_eq!(2, foo2.id());
}

#[test]
fn derive_identifiable_on_struct_with_non_integer_pk() {
    use associations::Identifiable;

    struct Foo {
        id: &'static str,
        #[allow(dead_code)]
        foo: i32,
    }

    Identifiable! {
        struct Foo {
            id: &'static str,
            foo: i32,
        }
    }

    let foo1 = Foo { id: "hi", foo: 2 };
    let foo2 = Foo { id: "there", foo: 3 };
    assert_eq!("hi", foo1.id());
    assert_eq!("there", foo2.id());
}
<commit_msg>Whoops, forgot to export Identifiable<commit_after>/// Implements the [`Identifiable`][identifiable] trait for a given struct. This
/// macro should be called by copy/pasting the definition of the struct into it.
///
/// The struct must have a field called `id`, and the type of that field must be
/// `Copy`. This macro does not work with tuple structs.
///
/// [identifiable]: query_source/trait.Identifiable.html
///
/// # Example
///
/// ```no_run
/// # #[macro_use] extern crate diesel;
/// struct User {
///     id: i32,
///     name: String,
/// }
///
/// Identifiable! {
///     struct User {
///         id: i32,
///         name: String,
///     }
/// }
/// # fn main() {}
/// ```
///
/// To avoid copying your struct definition, you can use the
/// [custom_derive crate][custom_derive].
///
/// [custom_derive]: https://crates.io/crates/custom_derive
///
/// ```ignore
/// custom_derive! {
///     #[derive(Identifiable)]
///     struct User {
///         id: i32,
///         name: String,
///     }
/// }
/// ```
#[macro_export]
macro_rules! Identifiable {
    // Strip empty argument list if given (Passed by custom_derive macro)
    (() $($body:tt)*) => {
        Identifiable! {
            $($body)*
        }
    };

    // Strip meta items, pub (if present) and struct from definition
    (
        $(#[$ignore:meta])*
        $(pub)* struct $($body:tt)*
    ) => {
        Identifiable! {
            $($body)*
        }
    };

    // We found the `id` field, return the final impl
    (
        (
            struct_ty = $struct_ty:ty,
        ),
        fields = [{
            field_name: id,
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        } $($fields:tt)*],
    ) => {
        impl $crate::associations::Identifiable for $struct_ty {
            type Id = $field_ty;

            fn id(&self) -> Self::Id {
                self.id
            }
        }
    };

    // Search for the `id` field and continue
    (
        (
            struct_ty = $struct_ty:ty,
        ),
        fields = [{
            field_name: $field_name:ident,
            column_name: $column_name:ident,
            field_ty: $field_ty:ty,
            field_kind: $field_kind:ident,
        } $($fields:tt)*],
    ) => {
        Identifiable! {
            (struct_ty = $struct_ty,),
            fields = [$($fields)*],
        }
    };

    // Handle struct with no generics
    (
        $struct_name:ident
        $body:tt $(;)*
    ) => {
        __diesel_parse_struct_body! {
            (
                struct_ty = $struct_name,
            ),
            callback = Identifiable,
            body = $body,
        }
    };
}

#[test]
fn derive_identifiable_on_simple_struct() {
    use associations::Identifiable;

    struct Foo {
        id: i32,
        #[allow(dead_code)]
        foo: i32,
    }

    Identifiable! {
        struct Foo {
            id: i32,
            foo: i32,
        }
    }

    let foo1 = Foo { id: 1, foo: 2 };
    let foo2 = Foo { id: 2, foo: 3 };
    assert_eq!(1, foo1.id());
    assert_eq!(2, foo2.id());
}

#[test]
fn derive_identifiable_when_id_is_not_first_field() {
    use associations::Identifiable;

    struct Foo {
        #[allow(dead_code)]
        foo: i32,
        id: i32,
    }

    Identifiable! {
        struct Foo {
            foo: i32,
            id: i32,
        }
    }

    let foo1 = Foo { id: 1, foo: 2 };
    let foo2 = Foo { id: 2, foo: 3 };
    assert_eq!(1, foo1.id());
    assert_eq!(2, foo2.id());
}

#[test]
fn derive_identifiable_on_struct_with_non_integer_pk() {
    use associations::Identifiable;

    struct Foo {
        id: &'static str,
        #[allow(dead_code)]
        foo: i32,
    }

    Identifiable! {
        struct Foo {
            id: &'static str,
            foo: i32,
        }
    }

    let foo1 = Foo { id: "hi", foo: 2 };
    let foo2 = Foo { id: "there", foo: 3 };
    assert_eq!("hi", foo1.id());
    assert_eq!("there", foo2.id());
}
<|endoftext|>