<commit_before>use nom::{self, IResult, Needed};

use std::io::{self, Read};
use std::ptr;
use std::cmp;

use super::StreamProducer;

/// Represent the different kinds of errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
  /// Error from I/O.
  IO(io::ErrorKind),
  /// A parser stopped midway and need more bytes to consume.
  Incomplete(usize),
  /// A parser has completes and there is still more bytes to consume.
  Continue,
  /// A parser has completes and there is no more bytes to consume.
  EndOfInput,
  /// A non-specified error.
  Unknown,
  // Parser Error
  /// Failed parsing the "fLaC" header token.
  HeaderParser,
  /// Failed parsing a metadata header.
  MetadataHeaderParser,
  /// Failed parsing the metadata block `StreamInfo`.
  StreamInfoParser,
  /// Failed parsing the metadata block `Padding`.
  PaddingParser,
  /// Failed parsing the metadata block `Application`.
  ApplicationParser,
  /// Failed parsing the metadata block `SeekTable`.
  SeekTableParser,
  /// Failed parsing the metadata block `VorbisComment`.
  VorbisCommentParser,
  /// Failed parsing the metadata block `CueSheet`.
  CueSheetParser,
  /// Failed parsing the metadata block `Picture`.
  PictureParser,
  /// Failed parsing the metadata block `Unknown`.
  UnknownParser,
  BlockingStrategyParser,
  BlockingSampleParser,
  ChannelBitsParser,
  UTF8HeaderParser,
  UTF8BodyParser,
  CRC8Parser,
  FrameFooterParser,
  // Invalid Error
  InvalidBlockType,
  InvalidSyncCode,
  InvalidBlockSample,
  InvalidChannelBits,
  InvalidUTF8,
  InvalidCRC8,
  InvalidCRC16,
  // Not Found
  NotFound,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T, ErrorKind> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(e)      => {
        match e {
          nom::Err::Code(k)               |
          nom::Err::Node(k, _)            |
          nom::Err::Position(k, _)        |
          nom::Err::NodePosition(k, _, _) => {
            if let nom::ErrorKind::Custom(kind) = k {
              Err(kind)
            } else {
              Err(ErrorKind::Unknown)
            }
          }
        }
      },
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T, ErrorKind>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity() + 1024;

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(e)      => {
      match e {
        nom::Err::Code(k)               |
        nom::Err::Node(k, _)            |
        nom::Err::Position(k, _)        |
        nom::Err::NodePosition(k, _, _) => {
          if let nom::ErrorKind::Custom(kind) = k {
            Err(kind)
          } else {
            Err(ErrorKind::Unknown)
          }
        }
      }
    },
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T, ErrorKind> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(|e| ErrorKind::IO(e.kind())));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        if let ErrorKind::Incomplete(needed) = kind {
          self.needed = needed;

          Err(ErrorKind::Continue)
        } else {
          Err(kind)
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::{self, IResult};

  #[inline]
  fn be_u32(input: &[u8]) -> IResult<&[u8], u32, ErrorKind> {
    nom::be_u32(input).map_err(to_custom_error!(Unknown))
  }

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<commit_msg>Add documentation for metadata block validity<commit_after>use nom::{self, IResult, Needed};

use std::io::{self, Read};
use std::ptr;
use std::cmp;

use super::StreamProducer;

/// Represent the different kinds of errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
  /// Error from I/O.
  IO(io::ErrorKind),
  /// A parser stopped midway and need more bytes to consume.
  Incomplete(usize),
  /// A parser has completes and there is still more bytes to consume.
  Continue,
  /// A parser has completes and there is no more bytes to consume.
  EndOfInput,
  /// A non-specified error.
  Unknown,
  // Parser Error
  /// Failed parsing the "fLaC" header token.
  HeaderParser,
  /// Failed parsing a metadata header.
  MetadataHeaderParser,
  /// Failed parsing the metadata block `StreamInfo`.
  StreamInfoParser,
  /// Failed parsing the metadata block `Padding`.
  PaddingParser,
  /// Failed parsing the metadata block `Application`.
  ApplicationParser,
  /// Failed parsing the metadata block `SeekTable`.
  SeekTableParser,
  /// Failed parsing the metadata block `VorbisComment`.
  VorbisCommentParser,
  /// Failed parsing the metadata block `CueSheet`.
  CueSheetParser,
  /// Failed parsing the metadata block `Picture`.
  PictureParser,
  /// Failed parsing the metadata block `Unknown`.
  UnknownParser,
  BlockingStrategyParser,
  BlockingSampleParser,
  ChannelBitsParser,
  UTF8HeaderParser,
  UTF8BodyParser,
  CRC8Parser,
  FrameFooterParser,
  // Invalid Error
  /// A block type, base on the number, that is outside the range (0-126).
  InvalidBlockType,
  InvalidSyncCode,
  InvalidBlockSample,
  InvalidChannelBits,
  InvalidUTF8,
  InvalidCRC8,
  InvalidCRC16,
  // Not Found
  NotFound,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T, ErrorKind> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(e)      => {
        match e {
          nom::Err::Code(k)               |
          nom::Err::Node(k, _)            |
          nom::Err::Position(k, _)        |
          nom::Err::NodePosition(k, _, _) => {
            if let nom::ErrorKind::Custom(kind) = k {
              Err(kind)
            } else {
              Err(ErrorKind::Unknown)
            }
          }
        }
      },
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T, ErrorKind>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity() + 1024;

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(e)      => {
      match e {
        nom::Err::Code(k)               |
        nom::Err::Node(k, _)            |
        nom::Err::Position(k, _)        |
        nom::Err::NodePosition(k, _, _) => {
          if let nom::ErrorKind::Custom(kind) = k {
            Err(kind)
          } else {
            Err(ErrorKind::Unknown)
          }
        }
      }
    },
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T, ErrorKind> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(|e| ErrorKind::IO(e.kind())));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        if let ErrorKind::Incomplete(needed) = kind {
          self.needed = needed;

          Err(ErrorKind::Continue)
        } else {
          Err(kind)
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::{self, IResult};

  #[inline]
  fn be_u32(input: &[u8]) -> IResult<&[u8], u32, ErrorKind> {
    nom::be_u32(input).map_err(to_custom_error!(Unknown))
  }

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<|endoftext|>


<commit_before>use nom::{Err, IResult, Needed};

use std::io;
use std::io::Read;
use std::ptr;
use std::cmp;

use super::StreamProducer;

#[derive(Debug)]
pub enum ErrorKind {
  IO(io::Error),
  Incomplete(usize),
  Consumed(usize),
  Continue,
  EndOfInput,
  Unknown,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(e)      => {
        if let Err::Position(_, i) = e {
          let consumed = self.len() - i.len();

          self.offset += consumed;

          Err(ErrorKind::Consumed(consumed))
        } else {
          Err(ErrorKind::Unknown)
        }
      }
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity();

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(_)      => Err(ErrorKind::Unknown),
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(ErrorKind::IO));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        match kind {
          ErrorKind::Incomplete(needed) => {
            self.needed = needed;

            Err(ErrorKind::Continue)
          }
          ErrorKind::Consumed(consumed) => {
            buffer.consume(consumed);

            Err(ErrorKind::Continue)
          }
          _                             => Err(kind),
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::be_u32;

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<commit_msg>Remove consume state within `ByteStream`<commit_after>use nom::{Err, IResult, Needed};

use std::io;
use std::io::Read;
use std::ptr;
use std::cmp;

use super::StreamProducer;

#[derive(Debug)]
pub enum ErrorKind {
  IO(io::Error),
  Incomplete(usize),
  Consumed(usize),
  Continue,
  EndOfInput,
  Unknown,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(_)      => Err(ErrorKind::Unknown),
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity();

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(_)      => Err(ErrorKind::Unknown),
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(ErrorKind::IO));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        match kind {
          ErrorKind::Incomplete(needed) => {
            self.needed = needed;

            Err(ErrorKind::Continue)
          }
          ErrorKind::Consumed(consumed) => {
            buffer.consume(consumed);

            Err(ErrorKind::Continue)
          }
          _                             => Err(kind),
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::be_u32;

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<|endoftext|>


<commit_before>use general::{ClosedDiv, ClosedMul, ClosedNeg, Id, Inverse, MultiplicativeGroup,
              MultiplicativeMonoid, Real, SubsetOf};
use linear::{EuclideanSpace, NormedSpace};

// NOTE: A subgroup trait inherit from its parent groups.

/// A general transformation acting on an euclidean space. It may not be inversible.
pub trait Transformation<E: EuclideanSpace>: MultiplicativeMonoid {
    /// Applies this group's action on a point from the euclidean space.
    fn transform_point(&self, pt: &E) -> E;

    /// Applies this group's action on a vector from the euclidean space.
    ///
    /// If `v` is a vector and `a, b` two point such that `v = a - b`, the action `∘` on a vector
    /// is defined as `self ∘ v = (self × a) - (self × b)`.
    fn transform_vector(&self, v: &E::Coordinates) -> E::Coordinates;
}

/// The most general form of inversible transformations on an euclidean space.
pub trait ProjectiveTransformation<E: EuclideanSpace>
    : MultiplicativeGroup + Transformation<E> {
    /// Applies this group's inverse action on a point from the euclidean space.
    fn inverse_transform_point(&self, pt: &E) -> E;

    /// Applies this group's inverse action on a vector from the euclidean space.
    ///
    /// If `v` is a vector and `a, b` two point such that `v = a - b`, the action `∘` on a vector
    /// is defined as `self ∘ v = (self × a) - (self × b)`.
    fn inverse_transform_vector(&self, v: &E::Coordinates) -> E::Coordinates;
}

/// The group of affine transformations. They are decomposable into a rotation, a non-uniform
/// scaling, a second rotation, and a translation (applied in that order).
pub trait AffineTransformation<E: EuclideanSpace>: ProjectiveTransformation<E> {
    /// Type of the first rotation to be applied.
    type Rotation: Rotation<E>;
    /// Type of the non-uniform scaling to be applied.
    type NonUniformScaling: AffineTransformation<E>;
    /// The type of the pure translation part of this affine transformation.
    type Translation: Translation<E>;

    /// Decomposes this affine transformation into a rotation followed by a non-uniform scaling,
    /// followed by a rotation, followed by a translation.
    fn decompose(
        &self,
    ) -> (
        Self::Translation,
        Self::Rotation,
        Self::NonUniformScaling,
        Self::Rotation,
    );
    // FIXME: add a `recompose` method?

    /*
     * Composition with components.
     */
    /// Appends a translation to this similarity.
    fn append_translation(&self, t: &Self::Translation) -> Self;

    /// Prepends a translation to this similarity.
    fn prepend_translation(&self, t: &Self::Translation) -> Self;

    /// Appends a rotation to this similarity.
    fn append_rotation(&self, r: &Self::Rotation) -> Self;

    /// Prepends a rotation to this similarity.
    fn prepend_rotation(&self, r: &Self::Rotation) -> Self;

    /// Appends a scaling factor to this similarity.
    fn append_scaling(&self, s: &Self::NonUniformScaling) -> Self;

    /// Prepends a scaling factor to this similarity.
    fn prepend_scaling(&self, s: &Self::NonUniformScaling) -> Self;

    /// Appends to this similarity a rotation centered at the point `p`, i.e., this point is left
    /// invariant.
    ///
    /// May return `None` if `Self` does not have enough translational degree of liberty to perform
    /// this computation.
    #[inline]
    fn append_rotation_wrt_point(&self, r: &Self::Rotation, p: &E) -> Option<Self> {
        if let Some(t) = Self::Translation::from_vector(p.coordinates()) {
            let it = t.inverse();
            Some(
                self.append_translation(&it)
                    .append_rotation(&r)
                    .append_translation(&t),
            )
        } else {
            None
        }
    }
}

/// Subgroups of the similarity group `S(n)`, i.e., rotations, translations, and (signed) uniform scaling.
///
/// Similarities map lines to lines and preserve angles.
pub trait Similarity<E: EuclideanSpace>
    : AffineTransformation<E, NonUniformScaling = <Self as Similarity<E>>::Scaling>
    {
    /// The type of the pure (uniform) scaling part of this similarity transformation.
    type Scaling: Scaling<E>;

    /*
     * Components retrieval.
     */
    /// The pure translational component of this similarity transformation.
    fn translation(&self) -> Self::Translation;

    /// The pure rotational component of this similarity transformation.
    fn rotation(&self) -> Self::Rotation;

    /// The pure scaling component of this similarity transformation.
    fn scaling(&self) -> Self::Scaling;

    /*
     * Transformations.
     */
    /// Applies this transformation's pure translational part to a point.
    #[inline]
    fn translate_point(&self, pt: &E) -> E {
        self.translation().transform_point(pt)
    }

    /// Applies this transformation's pure rotational part to a point.
    #[inline]
    fn rotate_point(&self, pt: &E) -> E {
        self.rotation().transform_point(pt)
    }

    /// Applies this transformation's pure scaling part to a point.
    #[inline]
    fn scale_point(&self, pt: &E) -> E {
        self.scaling().transform_point(pt)
    }

    /// Applies this transformation's pure rotational part to a vector.
    #[inline]
    fn rotate_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.rotation().transform_vector(pt)
    }

    /// Applies this transformation's pure scaling part to a vector.
    #[inline]
    fn scale_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.scaling().transform_vector(pt)
    }

    /*
     * Inverse transformations.
     */
    /// Applies this transformation inverse's pure translational part to a point.
    #[inline]
    fn inverse_translate_point(&self, pt: &E) -> E {
        self.translation().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure rotational part to a point.
    #[inline]
    fn inverse_rotate_point(&self, pt: &E) -> E {
        self.rotation().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure scaling part to a point.
    #[inline]
    fn inverse_scale_point(&self, pt: &E) -> E {
        self.scaling().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure rotational part to a vector.
    #[inline]
    fn inverse_rotate_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.rotation().inverse_transform_vector(pt)
    }

    /// Applies this transformation inverse's pure scaling part to a vector.
    #[inline]
    fn inverse_scale_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.scaling().inverse_transform_vector(pt)
    }
}

/// Subgroups of the isometry group `E(n)`, i.e., rotations, reflexions, and translations.
pub trait Isometry<E: EuclideanSpace>: Similarity<E, Scaling = Id> {}

/// Subgroups of the orientation-preserving isometry group `SE(n)`, i.e., rotations and translations.
pub trait DirectIsometry<E: EuclideanSpace>: Isometry<E> {}

/// Subgroups of the n-dimensional rotations and scaling `O(n)`.
pub trait OrthogonalTransformation<E: EuclideanSpace>
    : Isometry<E, Translation = Id> {
}

/// Subgroups of the (signed) uniform scaling group.
pub trait Scaling<E: EuclideanSpace>
    : AffineTransformation<E, NonUniformScaling = Self, Translation = Id, Rotation = Id>
    + SubsetOf<E::Real> {
    /// Converts this scaling factor to a real. Same as `self.to_superset()`.
    #[inline]
    fn to_real(&self) -> E::Real {
        self.to_superset()
    }

    /// Attempts to convert a real to an element of this scaling subgroup. Same as
    /// `Self::from_superset()`. Returns `None` if no such scaling is possible for this subgroup.
    #[inline]
    fn from_real(r: E::Real) -> Option<Self> {
        Self::from_superset(&r)
    }

    /// Raises the scaling to a power. The result must be equivalent to
    /// `self.to_superset().powf(n)`. Returns `None` if the result is not representable by `Self`.
    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Self::from_superset(&self.to_superset().powf(n))
    }

    /// The scaling required to make `a` have the same norm as `b`, i.e., `|b| = |a| * norm_ratio(a,
    /// b)`.
    #[inline]
    fn scale_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self> {
        Self::from_superset(&(b.norm() / a.norm()))
    }
}

/// Subgroups of the n-dimensional translation group `T(n)`.
pub trait Translation<E: EuclideanSpace>
    : DirectIsometry<E, Translation = Self, Rotation = Id> /* + SubsetOf<E::Coordinates> */ {
    // NOTE: we must define those two conversions here (instead of just using SubsetOf) because the
    // structure of Self uses the multiplication for composition, while E::Coordinates uses addition.
    // Having a trait that sais "remap this operator to this other one" does not seem to be
    // possible without higher kinded traits.
    /// Converts this translation to a vector.
    fn to_vector(&self) -> E::Coordinates;

    /// Attempts to convert a vector to this translation. Returns `None` if the translation
    /// represented by `v` is not part of the translation subgroup represented by `Self`.
    fn from_vector(v: E::Coordinates) -> Option<Self>;

    /// Raises the translation to a power. The result must be equivalent to
    /// `self.to_superset() * n`.  Returns `None` if the result is not representable by `Self`.
    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Self::from_vector(self.to_vector() * n)
    }

    /// The translation needed to make `a` coincide with `b`, i.e., `b = a * translation_to(a, b)`.
    #[inline]
    fn translation_between(a: &E, b: &E) -> Option<Self> {
        Self::from_vector(b.clone() - a.clone())
    }
}

/// Subgroups of the n-dimensional rotation group `SO(n)`.
pub trait Rotation<E: EuclideanSpace>
    : OrthogonalTransformation<E, Rotation = Self> + DirectIsometry<E, Rotation = Self>
    {
    /// Raises this rotation to a power. If this is a simple rotation, the result must be
    /// equivalent to multiplying the rotation angle by `n`.
    fn powf(&self, n: E::Real) -> Option<Self>;

    /// Computes a simple rotation that makes the angle between `a` and `b` equal to zero, i.e.,
    /// `b.angle(a * delta_rotation(a, b)) = 0`. If `a` and `b` are collinear, the computed
    /// rotation may not be unique. Returns `None` if no such simple rotation exists in the
    /// subgroup represented by `Self`.
    fn rotation_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self>;

    /// Computes the rotation between `a` and `b` and raises it to the power `n`.
    ///
    /// This is equivalent to calling `self.rotation_between(a, b)` followed by `.powf(n)` but will
    /// usually be much more efficient.
    #[inline]
    fn scaled_rotation_between(a: &E::Coordinates, b: &E::Coordinates, s: E::Real) -> Option<Self>;

    // FIXME: add a function that computes the rotation with the axis orthogonal to Span(a, b) and
    // with angle equal to `n`?
}

/*
 *
 * Implementation for floats.
 *
 */

impl<R, E> Transformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn transform_point(&self, pt: &E) -> E {
        pt.scale_by(*self)
    }

    #[inline]
    fn transform_vector(&self, v: &E::Coordinates) -> E::Coordinates {
        v.clone() * *self
    }
}

impl<R, E> ProjectiveTransformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn inverse_transform_point(&self, pt: &E) -> E {
        assert!(*self != R::zero());
        pt.scale_by(R::one() / *self)
    }

    #[inline]
    fn inverse_transform_vector(&self, v: &E::Coordinates) -> E::Coordinates {
        assert!(*self != R::zero());
        v.clone() * (R::one() / *self)
    }
}

impl<R, E> AffineTransformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    type Rotation = Id;
    type NonUniformScaling = R;
    type Translation = Id;

    #[inline]
    fn decompose(&self) -> (Id, Id, R, Id) {
        (Id::new(), Id::new(), *self, Id::new())
    }

    #[inline]
    fn append_translation(&self, _: &Self::Translation) -> Self {
        *self
    }

    #[inline]
    fn prepend_translation(&self, _: &Self::Translation) -> Self {
        *self
    }

    #[inline]
    fn append_rotation(&self, _: &Self::Rotation) -> Self {
        *self
    }

    #[inline]
    fn prepend_rotation(&self, _: &Self::Rotation) -> Self {
        *self
    }

    #[inline]
    fn append_scaling(&self, s: &Self::NonUniformScaling) -> Self {
        *s * *self
    }

    #[inline]
    fn prepend_scaling(&self, s: &Self::NonUniformScaling) -> Self {
        *self * *s
    }
}

impl<R, E> Scaling<E> for R
where
    R: Real + SubsetOf<R>,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn to_real(&self) -> E::Real {
        *self
    }

    #[inline]
    fn from_real(r: E::Real) -> Option<Self> {
        Some(r)
    }

    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Some(n.powf(n))
    }

    #[inline]
    fn scale_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self> {
        Some((b.norm() / a.norm()))
    }
}

impl<R, E> Similarity<E> for R
where
    R: Real + SubsetOf<R>,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    type Scaling = R;

    fn translation(&self) -> Self::Translation {
        Id::new()
    }

    fn rotation(&self) -> Self::Rotation {
        Id::new()
    }

    fn scaling(&self) -> Self::Scaling {
        *self
    }
}
<commit_msg>Remove useless parenthesis.<commit_after>use general::{ClosedDiv, ClosedMul, ClosedNeg, Id, Inverse, MultiplicativeGroup,
              MultiplicativeMonoid, Real, SubsetOf};
use linear::{EuclideanSpace, NormedSpace};

// NOTE: A subgroup trait inherit from its parent groups.

/// A general transformation acting on an euclidean space. It may not be inversible.
pub trait Transformation<E: EuclideanSpace>: MultiplicativeMonoid {
    /// Applies this group's action on a point from the euclidean space.
    fn transform_point(&self, pt: &E) -> E;

    /// Applies this group's action on a vector from the euclidean space.
    ///
    /// If `v` is a vector and `a, b` two point such that `v = a - b`, the action `∘` on a vector
    /// is defined as `self ∘ v = (self × a) - (self × b)`.
    fn transform_vector(&self, v: &E::Coordinates) -> E::Coordinates;
}

/// The most general form of inversible transformations on an euclidean space.
pub trait ProjectiveTransformation<E: EuclideanSpace>
    : MultiplicativeGroup + Transformation<E> {
    /// Applies this group's inverse action on a point from the euclidean space.
    fn inverse_transform_point(&self, pt: &E) -> E;

    /// Applies this group's inverse action on a vector from the euclidean space.
    ///
    /// If `v` is a vector and `a, b` two point such that `v = a - b`, the action `∘` on a vector
    /// is defined as `self ∘ v = (self × a) - (self × b)`.
    fn inverse_transform_vector(&self, v: &E::Coordinates) -> E::Coordinates;
}

/// The group of affine transformations. They are decomposable into a rotation, a non-uniform
/// scaling, a second rotation, and a translation (applied in that order).
pub trait AffineTransformation<E: EuclideanSpace>: ProjectiveTransformation<E> {
    /// Type of the first rotation to be applied.
    type Rotation: Rotation<E>;
    /// Type of the non-uniform scaling to be applied.
    type NonUniformScaling: AffineTransformation<E>;
    /// The type of the pure translation part of this affine transformation.
    type Translation: Translation<E>;

    /// Decomposes this affine transformation into a rotation followed by a non-uniform scaling,
    /// followed by a rotation, followed by a translation.
    fn decompose(
        &self,
    ) -> (
        Self::Translation,
        Self::Rotation,
        Self::NonUniformScaling,
        Self::Rotation,
    );
    // FIXME: add a `recompose` method?

    /*
     * Composition with components.
     */
    /// Appends a translation to this similarity.
    fn append_translation(&self, t: &Self::Translation) -> Self;

    /// Prepends a translation to this similarity.
    fn prepend_translation(&self, t: &Self::Translation) -> Self;

    /// Appends a rotation to this similarity.
    fn append_rotation(&self, r: &Self::Rotation) -> Self;

    /// Prepends a rotation to this similarity.
    fn prepend_rotation(&self, r: &Self::Rotation) -> Self;

    /// Appends a scaling factor to this similarity.
    fn append_scaling(&self, s: &Self::NonUniformScaling) -> Self;

    /// Prepends a scaling factor to this similarity.
    fn prepend_scaling(&self, s: &Self::NonUniformScaling) -> Self;

    /// Appends to this similarity a rotation centered at the point `p`, i.e., this point is left
    /// invariant.
    ///
    /// May return `None` if `Self` does not have enough translational degree of liberty to perform
    /// this computation.
    #[inline]
    fn append_rotation_wrt_point(&self, r: &Self::Rotation, p: &E) -> Option<Self> {
        if let Some(t) = Self::Translation::from_vector(p.coordinates()) {
            let it = t.inverse();
            Some(
                self.append_translation(&it)
                    .append_rotation(&r)
                    .append_translation(&t),
            )
        } else {
            None
        }
    }
}

/// Subgroups of the similarity group `S(n)`, i.e., rotations, translations, and (signed) uniform scaling.
///
/// Similarities map lines to lines and preserve angles.
pub trait Similarity<E: EuclideanSpace>
    : AffineTransformation<E, NonUniformScaling = <Self as Similarity<E>>::Scaling>
    {
    /// The type of the pure (uniform) scaling part of this similarity transformation.
    type Scaling: Scaling<E>;

    /*
     * Components retrieval.
     */
    /// The pure translational component of this similarity transformation.
    fn translation(&self) -> Self::Translation;

    /// The pure rotational component of this similarity transformation.
    fn rotation(&self) -> Self::Rotation;

    /// The pure scaling component of this similarity transformation.
    fn scaling(&self) -> Self::Scaling;

    /*
     * Transformations.
     */
    /// Applies this transformation's pure translational part to a point.
    #[inline]
    fn translate_point(&self, pt: &E) -> E {
        self.translation().transform_point(pt)
    }

    /// Applies this transformation's pure rotational part to a point.
    #[inline]
    fn rotate_point(&self, pt: &E) -> E {
        self.rotation().transform_point(pt)
    }

    /// Applies this transformation's pure scaling part to a point.
    #[inline]
    fn scale_point(&self, pt: &E) -> E {
        self.scaling().transform_point(pt)
    }

    /// Applies this transformation's pure rotational part to a vector.
    #[inline]
    fn rotate_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.rotation().transform_vector(pt)
    }

    /// Applies this transformation's pure scaling part to a vector.
    #[inline]
    fn scale_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.scaling().transform_vector(pt)
    }

    /*
     * Inverse transformations.
     */
    /// Applies this transformation inverse's pure translational part to a point.
    #[inline]
    fn inverse_translate_point(&self, pt: &E) -> E {
        self.translation().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure rotational part to a point.
    #[inline]
    fn inverse_rotate_point(&self, pt: &E) -> E {
        self.rotation().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure scaling part to a point.
    #[inline]
    fn inverse_scale_point(&self, pt: &E) -> E {
        self.scaling().inverse_transform_point(pt)
    }

    /// Applies this transformation inverse's pure rotational part to a vector.
    #[inline]
    fn inverse_rotate_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.rotation().inverse_transform_vector(pt)
    }

    /// Applies this transformation inverse's pure scaling part to a vector.
    #[inline]
    fn inverse_scale_vector(&self, pt: &E::Coordinates) -> E::Coordinates {
        self.scaling().inverse_transform_vector(pt)
    }
}

/// Subgroups of the isometry group `E(n)`, i.e., rotations, reflexions, and translations.
pub trait Isometry<E: EuclideanSpace>: Similarity<E, Scaling = Id> {}

/// Subgroups of the orientation-preserving isometry group `SE(n)`, i.e., rotations and translations.
pub trait DirectIsometry<E: EuclideanSpace>: Isometry<E> {}

/// Subgroups of the n-dimensional rotations and scaling `O(n)`.
pub trait OrthogonalTransformation<E: EuclideanSpace>
    : Isometry<E, Translation = Id> {
}

/// Subgroups of the (signed) uniform scaling group.
pub trait Scaling<E: EuclideanSpace>
    : AffineTransformation<E, NonUniformScaling = Self, Translation = Id, Rotation = Id>
    + SubsetOf<E::Real> {
    /// Converts this scaling factor to a real. Same as `self.to_superset()`.
    #[inline]
    fn to_real(&self) -> E::Real {
        self.to_superset()
    }

    /// Attempts to convert a real to an element of this scaling subgroup. Same as
    /// `Self::from_superset()`. Returns `None` if no such scaling is possible for this subgroup.
    #[inline]
    fn from_real(r: E::Real) -> Option<Self> {
        Self::from_superset(&r)
    }

    /// Raises the scaling to a power. The result must be equivalent to
    /// `self.to_superset().powf(n)`. Returns `None` if the result is not representable by `Self`.
    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Self::from_superset(&self.to_superset().powf(n))
    }

    /// The scaling required to make `a` have the same norm as `b`, i.e., `|b| = |a| * norm_ratio(a,
    /// b)`.
    #[inline]
    fn scale_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self> {
        Self::from_superset(&(b.norm() / a.norm()))
    }
}

/// Subgroups of the n-dimensional translation group `T(n)`.
pub trait Translation<E: EuclideanSpace>
    : DirectIsometry<E, Translation = Self, Rotation = Id> /* + SubsetOf<E::Coordinates> */ {
    // NOTE: we must define those two conversions here (instead of just using SubsetOf) because the
    // structure of Self uses the multiplication for composition, while E::Coordinates uses addition.
    // Having a trait that sais "remap this operator to this other one" does not seem to be
    // possible without higher kinded traits.
    /// Converts this translation to a vector.
    fn to_vector(&self) -> E::Coordinates;

    /// Attempts to convert a vector to this translation. Returns `None` if the translation
    /// represented by `v` is not part of the translation subgroup represented by `Self`.
    fn from_vector(v: E::Coordinates) -> Option<Self>;

    /// Raises the translation to a power. The result must be equivalent to
    /// `self.to_superset() * n`.  Returns `None` if the result is not representable by `Self`.
    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Self::from_vector(self.to_vector() * n)
    }

    /// The translation needed to make `a` coincide with `b`, i.e., `b = a * translation_to(a, b)`.
    #[inline]
    fn translation_between(a: &E, b: &E) -> Option<Self> {
        Self::from_vector(b.clone() - a.clone())
    }
}

/// Subgroups of the n-dimensional rotation group `SO(n)`.
pub trait Rotation<E: EuclideanSpace>
    : OrthogonalTransformation<E, Rotation = Self> + DirectIsometry<E, Rotation = Self>
    {
    /// Raises this rotation to a power. If this is a simple rotation, the result must be
    /// equivalent to multiplying the rotation angle by `n`.
    fn powf(&self, n: E::Real) -> Option<Self>;

    /// Computes a simple rotation that makes the angle between `a` and `b` equal to zero, i.e.,
    /// `b.angle(a * delta_rotation(a, b)) = 0`. If `a` and `b` are collinear, the computed
    /// rotation may not be unique. Returns `None` if no such simple rotation exists in the
    /// subgroup represented by `Self`.
    fn rotation_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self>;

    /// Computes the rotation between `a` and `b` and raises it to the power `n`.
    ///
    /// This is equivalent to calling `self.rotation_between(a, b)` followed by `.powf(n)` but will
    /// usually be much more efficient.
    #[inline]
    fn scaled_rotation_between(a: &E::Coordinates, b: &E::Coordinates, s: E::Real) -> Option<Self>;

    // FIXME: add a function that computes the rotation with the axis orthogonal to Span(a, b) and
    // with angle equal to `n`?
}

/*
 *
 * Implementation for floats.
 *
 */

impl<R, E> Transformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn transform_point(&self, pt: &E) -> E {
        pt.scale_by(*self)
    }

    #[inline]
    fn transform_vector(&self, v: &E::Coordinates) -> E::Coordinates {
        v.clone() * *self
    }
}

impl<R, E> ProjectiveTransformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn inverse_transform_point(&self, pt: &E) -> E {
        assert!(*self != R::zero());
        pt.scale_by(R::one() / *self)
    }

    #[inline]
    fn inverse_transform_vector(&self, v: &E::Coordinates) -> E::Coordinates {
        assert!(*self != R::zero());
        v.clone() * (R::one() / *self)
    }
}

impl<R, E> AffineTransformation<E> for R
where
    R: Real,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    type Rotation = Id;
    type NonUniformScaling = R;
    type Translation = Id;

    #[inline]
    fn decompose(&self) -> (Id, Id, R, Id) {
        (Id::new(), Id::new(), *self, Id::new())
    }

    #[inline]
    fn append_translation(&self, _: &Self::Translation) -> Self {
        *self
    }

    #[inline]
    fn prepend_translation(&self, _: &Self::Translation) -> Self {
        *self
    }

    #[inline]
    fn append_rotation(&self, _: &Self::Rotation) -> Self {
        *self
    }

    #[inline]
    fn prepend_rotation(&self, _: &Self::Rotation) -> Self {
        *self
    }

    #[inline]
    fn append_scaling(&self, s: &Self::NonUniformScaling) -> Self {
        *s * *self
    }

    #[inline]
    fn prepend_scaling(&self, s: &Self::NonUniformScaling) -> Self {
        *self * *s
    }
}

impl<R, E> Scaling<E> for R
where
    R: Real + SubsetOf<R>,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    #[inline]
    fn to_real(&self) -> E::Real {
        *self
    }

    #[inline]
    fn from_real(r: E::Real) -> Option<Self> {
        Some(r)
    }

    #[inline]
    fn powf(&self, n: E::Real) -> Option<Self> {
        Some(n.powf(n))
    }

    #[inline]
    fn scale_between(a: &E::Coordinates, b: &E::Coordinates) -> Option<Self> {
        Some(b.norm() / a.norm())
    }
}

impl<R, E> Similarity<E> for R
where
    R: Real + SubsetOf<R>,
    E: EuclideanSpace<Real = R>,
    E::Coordinates: ClosedMul<R> + ClosedDiv<R> + ClosedNeg,
{
    type Scaling = R;

    fn translation(&self) -> Self::Translation {
        Id::new()
    }

    fn rotation(&self) -> Self::Rotation {
        Id::new()
    }

    fn scaling(&self) -> Self::Scaling {
        *self
    }
}
<|endoftext|>


<commit_before>struct Owner(i32);

impl Owner {
    // Annotate lifetimes as in a standalone function.
    fn add_one<'a>(&'a mut self) { self.0 += 1 }
    fn print<'a>(&'a self) {
        println!("`print`: {}", self.0);
    }
}

fn main() {
    let mut owner  = Owner(18);

    owner.add_one();
    owner.print();
}
<commit_msg>Explicit add_one return value<commit_after>struct Owner(i32);

impl Owner {
    // Annotate lifetimes as in a standalone function.
    fn add_one<'a>(&'a mut self) { self.0 += 1; }
    fn print<'a>(&'a self) {
        println!("`print`: {}", self.0);
    }
}

fn main() {
    let mut owner  = Owner(18);

    owner.add_one();
    owner.print();
}
<|endoftext|>


<commit_before>// pp-exact

// The next line should not be expanded

#[path = "issue-12590-b.rs"]
mod issue_12590_b;

fn main() { }
<commit_msg>use pretty-compare-only in a test<commit_after>// pp-exact
// pretty-compare-only

// The next line should not be expanded

#[path = "issue-12590-b.rs"]
mod issue_12590_b;

fn main() { }
<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt::{Error, Formatter};
use std::rc::Rc;

use super::{Closable, RecursionTracker, Type, TypeError, TypeResult};

/// Proxy so that we can share different kinds of scopes.
#[derive(Clone, Debug)]
pub enum Scope {
    Func(Rc<RefCell<FuncScope>>),
    Module(Rc<RefCell<ModuleScope>>),
}

impl Scope {
    pub fn get_local(&self, name: &str) -> TypeResult<Type> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().get_local(name),
            Module(module) => module.borrow_mut().get_local(name),
        }
    }

    /// Called by a child scope to get its parent's local.
    ///
    ///     return self.parent.get_local_from_parent(name);
    ///
    pub fn get_local_from_parent(&self, name: &str) -> TypeResult<(Type, ParentResolution)> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().get_local_as_parent(name),
            Module(module) => module.borrow_mut().get_local_as_parent(name),
        }
    }

    pub fn add_local(&self, name: &str, typ: Type) -> TypeResult<()> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().add_local(name, typ),
            Module(module) => module.borrow_mut().add_local(name, typ),
        }
    }

    fn get_parent(&self) -> Option<Scope> {
        use Scope::*;
        match self {
            Func(func) => func.borrow().get_parent(),
            Module(module) => module.borrow().get_parent(),
        }
    }

    // Returns true if the other scope is a parent (or parent's parent, etc.)
    // of this scope. Also returns true if they're the same scope.
    pub fn within(&self, other: &Scope) -> bool {
        let mut parent = self.clone();
        // println!("begin within self: {:?} parent: {:?}", self, parent);
        loop {
            // println!("within parent: {:?} other: {:?} ==: {:?}", parent, other, &parent == other);
            if &parent == other {
                return true;
            }
            parent = if let Some(next) = parent.get_parent() {
                next
            } else {
                return false;
            }
        }
    }
}

impl Closable for Scope {
    fn close(self, tracker: &mut RecursionTracker, scope: Scope) -> TypeResult<Self> {
        use Scope::*;
        Ok(match self {
            Func(shared) => {
                let replacement = {
                    let func = shared.borrow();
                    let mut locals = HashMap::new();
                    for (name, typ) in func.locals.iter() {
                        locals.insert(name.clone(), typ.clone().close(tracker, scope.clone())?);
                    }
                    FuncScope {
                        locals,
                        parent: func.parent.clone(),
                        captures: func.captures,
                        captured: func.captured,
                        captured_locals: func.captured_locals.clone(),
                    }
                };
                shared.replace(replacement);
                Func(shared)
            }
            Module(shared) => {
                let replacement = {
                    let module = shared.borrow();
                    let mut statics = HashMap::new();
                    for (name, typ) in module.statics.iter() {
                        statics.insert(name.clone(), typ.clone().close(tracker, scope.clone())?);
                    }
                    ModuleScope {
                        statics,
                        captured_statics: module.captured_statics.clone(),
                    }
                };
                shared.replace(replacement);
                Module(shared)
            }
        })
    }
}

impl PartialEq for Scope {
    fn eq(&self, other: &Self) -> bool {
        use Scope::*;
        match (self, other) {
            (Func(self_func), Func(other_func)) => self_func.as_ptr() == other_func.as_ptr(),
            (Module(self_module), Module(other_module)) => {
                self_module.as_ptr() == other_module.as_ptr()
            }
            _ => false,
        }
    }
}

/// When getting locals from parent scopes we need to know if it was a local
/// that was ultimately read (need to set up closures) or if it was a static
/// (no need for closures).
pub enum ParentResolution {
    Local,
    Static,
}

pub trait ScopeLike {
    /// Consume oneself to produce a shareable `Scope`.
    fn into_scope(self) -> Scope;

    fn get_local(&mut self, name: &str) -> TypeResult<Type>;

    fn get_local_as_parent(&mut self, name: &str) -> TypeResult<(Type, ParentResolution)>;

    fn add_local(&mut self, name: &str, typ: Type) -> TypeResult<()>;

    fn get_parent(&self) -> Option<Scope>;
}

pub struct FuncScope {
    pub locals: HashMap<String, Type>,
    parent: Option<Scope>,
    /// Whether or not this scope captures its parent scope.
    captures: bool,
    /// Whether or not this scope (or one of its parent scopes) is captured
    /// by child scopes (closures).
    captured: bool,
    /// Locals in this scope which are captured by closures.
    captured_locals: HashSet<String>,
}

impl FuncScope {
    pub fn new(parent: Option<Scope>) -> Self {
        Self {
            locals: HashMap::new(),
            parent,
            captures: false,
            captured: false,
            captured_locals: HashSet::new(),
        }
    }
}

impl ScopeLike for FuncScope {
    fn into_scope(self) -> Scope {
        Scope::Func(Rc::new(RefCell::new(self)))
    }

    fn get_local(&mut self, name: &str) -> Result<Type, TypeError> {
        if let Some(typ) = self.locals.get(name) {
            return Ok(typ.clone());
        }
        if let Some(parent) = &self.parent {
            return match parent.get_local_from_parent(name) {
                Ok((typ, resolution)) => {
                    match resolution {
                        // If the ultimate resolution was as a local variable
                        // then we need to mark ourselves as capturing our
                        // parent's scope.
                        ParentResolution::Local => self.captures = true,
                        _ => (),
                    }
                    Ok(typ)
                }
                Err(err) => Err(err),
            };
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn get_local_as_parent(&mut self, name: &str) -> TypeResult<(Type, ParentResolution)> {
        if let Some(typ) = self.locals.get(name) {
            // If we found it in ourselves.
            self.captured = true;
            self.captured_locals.insert(name.to_string());
            return Ok((typ.clone(), ParentResolution::Local));
        }

        if let Some(parent) = &self.parent {
            return match parent.get_local_from_parent(name) {
                Ok((typ, resolution)) => {
                    match resolution {
                        // If the ultimate resolution was as a local variable
                        // then we need to mark ourselves as both captured and
                        // as capturing.
                        ParentResolution::Local => {
                            self.captures = true;
                            self.captured = true;
                        }
                        _ => (),
                    }
                    Ok((typ, resolution))
                }
                err @ Err(_) => err,
            };
        }

        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn add_local(&mut self, name: &str, typ: Type) -> Result<(), TypeError> {
        if self.locals.contains_key(name) {
            return Err(TypeError::LocalAlreadyDefined {
                name: name.to_string(),
            });
        }
        self.locals.insert(name.to_string(), typ);
        Ok(())
    }

    fn get_parent(&self) -> Option<Scope> {
        self.parent.clone()
    }
}

impl std::fmt::Debug for FuncScope {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(f, "FuncScope({:p})", self)
    }
}

pub struct ModuleScope {
    pub statics: HashMap<String, Type>,
    captured_statics: HashSet<String>,
}

impl ModuleScope {
    pub fn new() -> Self {
        Self {
            statics: HashMap::new(),
            captured_statics: HashSet::new(),
        }
    }
}

impl ScopeLike for ModuleScope {
    fn into_scope(self) -> Scope {
        Scope::Module(Rc::new(RefCell::new(self)))
    }

    fn get_local(&mut self, name: &str) -> Result<Type, TypeError> {
        if let Some(typ) = self.statics.get(name) {
            return Ok(typ.clone());
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn get_local_as_parent(&mut self, name: &str) -> Result<(Type, ParentResolution), TypeError> {
        if let Some(typ) = self.statics.get(name) {
            self.captured_statics.insert(name.to_string());
            return Ok((typ.clone(), ParentResolution::Static));
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn add_local(&mut self, name: &str, typ: Type) -> Result<(), TypeError> {
        if self.statics.contains_key(name) {
            return Err(TypeError::LocalAlreadyDefined {
                name: name.to_string(),
            });
        }
        self.statics.insert(name.to_string(), typ);
        Ok(())
    }

    fn get_parent(&self) -> Option<Scope> {
        None
    }
}

impl std::fmt::Debug for ModuleScope {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(f, "ModuleScope({:p})", self)
    }
}
<commit_msg>Remove two commented-out `println`s that snuck through<commit_after>use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt::{Error, Formatter};
use std::rc::Rc;

use super::{Closable, RecursionTracker, Type, TypeError, TypeResult};

/// Proxy so that we can share different kinds of scopes.
#[derive(Clone, Debug)]
pub enum Scope {
    Func(Rc<RefCell<FuncScope>>),
    Module(Rc<RefCell<ModuleScope>>),
}

impl Scope {
    pub fn get_local(&self, name: &str) -> TypeResult<Type> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().get_local(name),
            Module(module) => module.borrow_mut().get_local(name),
        }
    }

    /// Called by a child scope to get its parent's local.
    ///
    ///     return self.parent.get_local_from_parent(name);
    ///
    pub fn get_local_from_parent(&self, name: &str) -> TypeResult<(Type, ParentResolution)> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().get_local_as_parent(name),
            Module(module) => module.borrow_mut().get_local_as_parent(name),
        }
    }

    pub fn add_local(&self, name: &str, typ: Type) -> TypeResult<()> {
        use Scope::*;
        match self {
            Func(func) => func.borrow_mut().add_local(name, typ),
            Module(module) => module.borrow_mut().add_local(name, typ),
        }
    }

    fn get_parent(&self) -> Option<Scope> {
        use Scope::*;
        match self {
            Func(func) => func.borrow().get_parent(),
            Module(module) => module.borrow().get_parent(),
        }
    }

    // Returns true if the other scope is a parent (or parent's parent, etc.)
    // of this scope. Also returns true if they're the same scope.
    pub fn within(&self, other: &Scope) -> bool {
        let mut parent = self.clone();
        loop {
            if &parent == other {
                return true;
            }
            parent = if let Some(next) = parent.get_parent() {
                next
            } else {
                return false;
            }
        }
    }
}

impl Closable for Scope {
    fn close(self, tracker: &mut RecursionTracker, scope: Scope) -> TypeResult<Self> {
        use Scope::*;
        Ok(match self {
            Func(shared) => {
                let replacement = {
                    let func = shared.borrow();
                    let mut locals = HashMap::new();
                    for (name, typ) in func.locals.iter() {
                        locals.insert(name.clone(), typ.clone().close(tracker, scope.clone())?);
                    }
                    FuncScope {
                        locals,
                        parent: func.parent.clone(),
                        captures: func.captures,
                        captured: func.captured,
                        captured_locals: func.captured_locals.clone(),
                    }
                };
                shared.replace(replacement);
                Func(shared)
            }
            Module(shared) => {
                let replacement = {
                    let module = shared.borrow();
                    let mut statics = HashMap::new();
                    for (name, typ) in module.statics.iter() {
                        statics.insert(name.clone(), typ.clone().close(tracker, scope.clone())?);
                    }
                    ModuleScope {
                        statics,
                        captured_statics: module.captured_statics.clone(),
                    }
                };
                shared.replace(replacement);
                Module(shared)
            }
        })
    }
}

impl PartialEq for Scope {
    fn eq(&self, other: &Self) -> bool {
        use Scope::*;
        match (self, other) {
            (Func(self_func), Func(other_func)) => self_func.as_ptr() == other_func.as_ptr(),
            (Module(self_module), Module(other_module)) => {
                self_module.as_ptr() == other_module.as_ptr()
            }
            _ => false,
        }
    }
}

/// When getting locals from parent scopes we need to know if it was a local
/// that was ultimately read (need to set up closures) or if it was a static
/// (no need for closures).
pub enum ParentResolution {
    Local,
    Static,
}

pub trait ScopeLike {
    /// Consume oneself to produce a shareable `Scope`.
    fn into_scope(self) -> Scope;

    fn get_local(&mut self, name: &str) -> TypeResult<Type>;

    fn get_local_as_parent(&mut self, name: &str) -> TypeResult<(Type, ParentResolution)>;

    fn add_local(&mut self, name: &str, typ: Type) -> TypeResult<()>;

    fn get_parent(&self) -> Option<Scope>;
}

pub struct FuncScope {
    pub locals: HashMap<String, Type>,
    parent: Option<Scope>,
    /// Whether or not this scope captures its parent scope.
    captures: bool,
    /// Whether or not this scope (or one of its parent scopes) is captured
    /// by child scopes (closures).
    captured: bool,
    /// Locals in this scope which are captured by closures.
    captured_locals: HashSet<String>,
}

impl FuncScope {
    pub fn new(parent: Option<Scope>) -> Self {
        Self {
            locals: HashMap::new(),
            parent,
            captures: false,
            captured: false,
            captured_locals: HashSet::new(),
        }
    }
}

impl ScopeLike for FuncScope {
    fn into_scope(self) -> Scope {
        Scope::Func(Rc::new(RefCell::new(self)))
    }

    fn get_local(&mut self, name: &str) -> Result<Type, TypeError> {
        if let Some(typ) = self.locals.get(name) {
            return Ok(typ.clone());
        }
        if let Some(parent) = &self.parent {
            return match parent.get_local_from_parent(name) {
                Ok((typ, resolution)) => {
                    match resolution {
                        // If the ultimate resolution was as a local variable
                        // then we need to mark ourselves as capturing our
                        // parent's scope.
                        ParentResolution::Local => self.captures = true,
                        _ => (),
                    }
                    Ok(typ)
                }
                Err(err) => Err(err),
            };
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn get_local_as_parent(&mut self, name: &str) -> TypeResult<(Type, ParentResolution)> {
        if let Some(typ) = self.locals.get(name) {
            // If we found it in ourselves.
            self.captured = true;
            self.captured_locals.insert(name.to_string());
            return Ok((typ.clone(), ParentResolution::Local));
        }

        if let Some(parent) = &self.parent {
            return match parent.get_local_from_parent(name) {
                Ok((typ, resolution)) => {
                    match resolution {
                        // If the ultimate resolution was as a local variable
                        // then we need to mark ourselves as both captured and
                        // as capturing.
                        ParentResolution::Local => {
                            self.captures = true;
                            self.captured = true;
                        }
                        _ => (),
                    }
                    Ok((typ, resolution))
                }
                err @ Err(_) => err,
            };
        }

        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn add_local(&mut self, name: &str, typ: Type) -> Result<(), TypeError> {
        if self.locals.contains_key(name) {
            return Err(TypeError::LocalAlreadyDefined {
                name: name.to_string(),
            });
        }
        self.locals.insert(name.to_string(), typ);
        Ok(())
    }

    fn get_parent(&self) -> Option<Scope> {
        self.parent.clone()
    }
}

impl std::fmt::Debug for FuncScope {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(f, "FuncScope({:p})", self)
    }
}

pub struct ModuleScope {
    pub statics: HashMap<String, Type>,
    captured_statics: HashSet<String>,
}

impl ModuleScope {
    pub fn new() -> Self {
        Self {
            statics: HashMap::new(),
            captured_statics: HashSet::new(),
        }
    }
}

impl ScopeLike for ModuleScope {
    fn into_scope(self) -> Scope {
        Scope::Module(Rc::new(RefCell::new(self)))
    }

    fn get_local(&mut self, name: &str) -> Result<Type, TypeError> {
        if let Some(typ) = self.statics.get(name) {
            return Ok(typ.clone());
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn get_local_as_parent(&mut self, name: &str) -> Result<(Type, ParentResolution), TypeError> {
        if let Some(typ) = self.statics.get(name) {
            self.captured_statics.insert(name.to_string());
            return Ok((typ.clone(), ParentResolution::Static));
        }
        Err(TypeError::LocalNotFound {
            name: name.to_string(),
        })
    }

    fn add_local(&mut self, name: &str, typ: Type) -> Result<(), TypeError> {
        if self.statics.contains_key(name) {
            return Err(TypeError::LocalAlreadyDefined {
                name: name.to_string(),
            });
        }
        self.statics.insert(name.to_string(), typ);
        Ok(())
    }

    fn get_parent(&self) -> Option<Scope> {
        None
    }
}

impl std::fmt::Debug for ModuleScope {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(f, "ModuleScope({:p})", self)
    }
}
<|endoftext|>


<commit_before>use std::fmt;
use wlroots_sys::{wlr_keyboard, wlr_keyboard_get_modifiers, wlr_keyboard_led,
                  wlr_keyboard_led_update, wlr_keyboard_modifier, wlr_keyboard_set_keymap,
                  xkb_keymap};

#[derive(Debug)]
pub struct Keyboard {
    keyboard: *mut wlr_keyboard,
}

impl Keyboard {
    pub(crate) fn new(kb_pointer: *mut wlr_keyboard) -> Self {
        Keyboard { keyboard: kb_pointer }
    }

    pub(crate) unsafe fn to_ptr(&self) -> *mut wlr_keyboard {
        self.keyboard
    }

    // TODO: Implement keymap wrapper?
    pub fn set_keymap(&mut self, keymap: *mut xkb_keymap) {
        unsafe {
            wlr_keyboard_set_keymap(self.keyboard, keymap);
        }
    }

    pub fn led_update(&mut self, leds: KeyboardLed) {
        unsafe {
            wlr_keyboard_led_update(self.keyboard, leds.state());
        }
    }

    pub fn get_modifiers(&self) -> KeyboardModifier {
        unsafe { KeyboardModifier::new(wlr_keyboard_get_modifiers(self.keyboard)) }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeyboardLed {
    state: u32,
}

impl KeyboardLed {
    pub fn new(num_lock: bool, caps_lock: bool, scroll_lock: bool) -> Self {
        let mut state = 0;

        if num_lock {
            state |= wlr_keyboard_led::WLR_LED_NUM_LOCK as u32
        };

        if caps_lock {
            state |= wlr_keyboard_led::WLR_LED_CAPS_LOCK as u32
        }

        if scroll_lock {
            state |= wlr_keyboard_led::WLR_LED_SCROLL_LOCK as u32
        }

        KeyboardLed { state: state }
    }

    fn state(&self) -> u32 {
        self.state
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeyboardModifier {
    modifiers: u32,
}

macro_rules! keyboard_modifier_accessor {
    ($func_name: ident, $c_enum: expr) => [
        pub fn $func_name(&self) -> bool {
            (self.modifiers | $c_enum as u32) != 0
        }
    ]
}

impl KeyboardModifier {
    fn new(modifiers: u32) -> Self {
        KeyboardModifier { modifiers: modifiers }
    }

    keyboard_modifier_accessor!(shift, wlr_keyboard_modifier::WLR_MODIFIER_SHIFT);
    keyboard_modifier_accessor!(caps, wlr_keyboard_modifier::WLR_MODIFIER_CAPS);
    keyboard_modifier_accessor!(ctrl, wlr_keyboard_modifier::WLR_MODIFIER_CTRL);
    keyboard_modifier_accessor!(alt, wlr_keyboard_modifier::WLR_MODIFIER_ALT);
    keyboard_modifier_accessor!(mod2, wlr_keyboard_modifier::WLR_MODIFIER_MOD2);
    keyboard_modifier_accessor!(mod3, wlr_keyboard_modifier::WLR_MODIFIER_MOD3);
    keyboard_modifier_accessor!(logo, wlr_keyboard_modifier::WLR_MODIFIER_LOGO);
    keyboard_modifier_accessor!(mod5, wlr_keyboard_modifier::WLR_MODIFIER_MOD5);
}

impl fmt::Display for KeyboardModifier {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let mod_vec: Vec<(&str, &Fn(&KeyboardModifier) -> bool)> =
            vec![("Shift", &KeyboardModifier::shift),
                 ("Caps lock", &KeyboardModifier::caps),
                 ("Ctrl", &KeyboardModifier::ctrl),
                 ("Alt", &KeyboardModifier::alt),
                 ("Mod2", &KeyboardModifier::mod2),
                 ("Mod3", &KeyboardModifier::mod3),
                 ("Logo", &KeyboardModifier::logo),
                 ("Mod5", &KeyboardModifier::mod5)];

        let mods: Vec<&str> = mod_vec.into_iter()
            .filter(|&(_, func)| func(self))
            .map(|(st, _)| st)
            .collect();

        write!(formatter, "Modifiers: {:?}", mods)
    }
}<commit_msg>Fix modifiers display function<commit_after>use std::fmt;
use wlroots_sys::{wlr_keyboard, wlr_keyboard_get_modifiers, wlr_keyboard_led,
                  wlr_keyboard_led_update, wlr_keyboard_modifier, wlr_keyboard_set_keymap,
                  xkb_keymap};

#[derive(Debug)]
pub struct Keyboard {
    keyboard: *mut wlr_keyboard,
}

impl Keyboard {
    pub(crate) fn new(kb_pointer: *mut wlr_keyboard) -> Self {
        Keyboard { keyboard: kb_pointer }
    }

    pub(crate) unsafe fn to_ptr(&self) -> *mut wlr_keyboard {
        self.keyboard
    }

    // TODO: Implement keymap wrapper?
    pub fn set_keymap(&mut self, keymap: *mut xkb_keymap) {
        unsafe {
            wlr_keyboard_set_keymap(self.keyboard, keymap);
        }
    }

    pub fn led_update(&mut self, leds: KeyboardLed) {
        unsafe {
            wlr_keyboard_led_update(self.keyboard, leds.state());
        }
    }

    pub fn get_modifiers(&self) -> KeyboardModifier {
        unsafe { KeyboardModifier::new(wlr_keyboard_get_modifiers(self.keyboard)) }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeyboardLed {
    state: u32,
}

impl KeyboardLed {
    pub fn new(num_lock: bool, caps_lock: bool, scroll_lock: bool) -> Self {
        let mut state = 0;

        if num_lock {
            state |= wlr_keyboard_led::WLR_LED_NUM_LOCK as u32
        };

        if caps_lock {
            state |= wlr_keyboard_led::WLR_LED_CAPS_LOCK as u32
        }

        if scroll_lock {
            state |= wlr_keyboard_led::WLR_LED_SCROLL_LOCK as u32
        }

        KeyboardLed { state: state }
    }

    fn state(&self) -> u32 {
        self.state
    }
}

#[derive(Debug, Clone, Copy)]
pub struct KeyboardModifier {
    modifiers: u32,
}

macro_rules! keyboard_modifier_accessor {
    ($func_name: ident, $c_enum: expr) => [
        pub fn $func_name(&self) -> bool {
            (self.modifiers & $c_enum as u32) != 0
        }
    ]
}

impl KeyboardModifier {
    fn new(modifiers: u32) -> Self {
        KeyboardModifier { modifiers: modifiers }
    }

    keyboard_modifier_accessor!(shift, wlr_keyboard_modifier::WLR_MODIFIER_SHIFT);
    keyboard_modifier_accessor!(caps, wlr_keyboard_modifier::WLR_MODIFIER_CAPS);
    keyboard_modifier_accessor!(ctrl, wlr_keyboard_modifier::WLR_MODIFIER_CTRL);
    keyboard_modifier_accessor!(alt, wlr_keyboard_modifier::WLR_MODIFIER_ALT);
    keyboard_modifier_accessor!(mod2, wlr_keyboard_modifier::WLR_MODIFIER_MOD2);
    keyboard_modifier_accessor!(mod3, wlr_keyboard_modifier::WLR_MODIFIER_MOD3);
    keyboard_modifier_accessor!(logo, wlr_keyboard_modifier::WLR_MODIFIER_LOGO);
    keyboard_modifier_accessor!(mod5, wlr_keyboard_modifier::WLR_MODIFIER_MOD5);
}

impl fmt::Display for KeyboardModifier {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let mod_vec: Vec<(&str, &Fn(&KeyboardModifier) -> bool)> =
            vec![("Shift", &KeyboardModifier::shift),
                 ("Caps lock", &KeyboardModifier::caps),
                 ("Ctrl", &KeyboardModifier::ctrl),
                 ("Alt", &KeyboardModifier::alt),
                 ("Mod2", &KeyboardModifier::mod2),
                 ("Mod3", &KeyboardModifier::mod3),
                 ("Logo", &KeyboardModifier::logo),
                 ("Mod5", &KeyboardModifier::mod5)];

        let mods: Vec<&str> = mod_vec.into_iter()
            .filter(|&(_, func)| func(self))
            .map(|(st, _)| st)
            .collect();

        write!(formatter, "{:?}", mods)
    }
}<|endoftext|>