<commit_before>use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File as FSFile;
use std::ops::Deref;
use std::io::Write;
use std::io::Read;

pub mod path;
pub mod file;
pub mod parser;
pub mod json;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use storage::parser::{FileHeaderParser, Parser, ParserError};
use storage::file::header::data::FileHeaderData;

type Cache = HashMap<FileID, Rc<RefCell<File>>>;

pub struct Store {
    storepath: String,
    cache : RefCell<Cache>,
}

impl Store {

    pub fn new(storepath: String) -> Store {
        Store {
            storepath: storepath,
            cache: RefCell::new(HashMap::new()),
        }
    }

    fn put_in_cache(&self, f: File) -> FileID {
        let res = f.id().clone();
        self.cache.borrow_mut().insert(f.id().clone(), Rc::new(RefCell::new(f)));
        res
    }

    pub fn load_in_cache<HP>(&self, m: &Module, parser: &Parser<HP>, id: FileID)
        -> Option<Rc<RefCell<File>>>
        where HP: FileHeaderParser
    {
        let idstr : String = id.clone().into();
        let path = format!("{}/{}-{}.imag", self.storepath, m.name(), idstr);
        let mut string = String::new();

        FSFile::open(&path).map(|mut file| {
            file.read_to_string(&mut string)
                .map_err(|e| error!("Failed reading file: '{}'", path));
        });

        parser.read(string).map(|(header, data)| {
            self.new_file_from_parser_result(m, id.clone(), header, data);
        });

        self.load(&id)
    }

    pub fn new_file(&self, module: &Module)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: String::from(""),
            id: self.get_new_file_id(),
        };

        debug!("Create new File object: {:?}", &f);
        self.put_in_cache(f)
    }

    pub fn new_file_from_parser_result(&self,
                                       module: &Module,
                                       id: FileID,
                                       header: FileHeaderData,
                                       data: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: header,
            data: data,
            id: id,
        };
        debug!("Create new File object from parser result: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_header(&self,
                                module: &Module,
                                h: FileHeaderData)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: String::from(""),
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with header: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_data(&self, module: &Module, d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with data: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_content(&self,
                                 module: &Module,
                                 h: FileHeaderData,
                                 d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with content: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn persist<HP>(&self,
                       p: &Parser<HP>,
                       f: Rc<RefCell<File>>) -> bool
        where HP: FileHeaderParser
    {
        let file = f.deref().borrow();
        let text = p.write(file.contents());
        if text.is_err() {
            error!("Error: {}", text.err().unwrap());
            return false;
        }

        let path = {
            let ids : String = file.id().clone().into();
            format!("{}/{}-{}.imag", self.storepath, file.owning_module_name, ids)
        };

        self.ensure_store_path_exists();

        FSFile::create(&path).map(|mut fsfile| {
            fsfile.write_all(&text.unwrap().clone().into_bytes()[..])
        }).map_err(|writeerr|  {
            debug!("Could not create file at '{}'", path);
        }).and(Ok(true)).unwrap()
    }

    fn ensure_store_path_exists(&self) {
        use std::fs::create_dir_all;
        use std::process::exit;

        create_dir_all(&self.storepath).unwrap_or_else(|e| {
            error!("Could not create store: '{}'", self.storepath);
            error!("Error                 : '{}'", e);
            error!("Killing myself now");
            exit(1);
        })
    }

    pub fn load(&self, id: &FileID) -> Option<Rc<RefCell<File>>> {
        debug!("Loading '{:?}'", id);
        self.cache.borrow().get(id).cloned()
    }

    pub fn remove(&self, id: FileID) -> bool {
        use std::fs::remove_file;

        self.cache
            .borrow_mut()
            .remove(&id)
            .map(|file| {
                let idstr : String = id.into();
                let path = format!("{}/{}-{}.imag",
                                   self.storepath,
                                   file.deref().borrow().owner_name(),
                                   idstr);
                remove_file(path).is_ok()
            })
            .unwrap_or(false)
    }

    fn get_new_file_id(&self) -> FileID {
        use uuid::Uuid;
        let hash = FileHash::from(Uuid::new_v4().to_hyphenated_string());
        FileID::new(FileIDType::UUID, hash)
    }

}
<commit_msg>Add Store::load_for_module()<commit_after>use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File as FSFile;
use std::ops::Deref;
use std::io::Write;
use std::io::Read;

pub mod path;
pub mod file;
pub mod parser;
pub mod json;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use storage::parser::{FileHeaderParser, Parser, ParserError};
use storage::file::header::data::FileHeaderData;

type Cache = HashMap<FileID, Rc<RefCell<File>>>;

pub struct Store {
    storepath: String,
    cache : RefCell<Cache>,
}

impl Store {

    pub fn new(storepath: String) -> Store {
        Store {
            storepath: storepath,
            cache: RefCell::new(HashMap::new()),
        }
    }

    fn put_in_cache(&self, f: File) -> FileID {
        let res = f.id().clone();
        self.cache.borrow_mut().insert(f.id().clone(), Rc::new(RefCell::new(f)));
        res
    }

    pub fn load_in_cache<HP>(&self, m: &Module, parser: &Parser<HP>, id: FileID)
        -> Option<Rc<RefCell<File>>>
        where HP: FileHeaderParser
    {
        let idstr : String = id.clone().into();
        let path = format!("{}/{}-{}.imag", self.storepath, m.name(), idstr);
        let mut string = String::new();

        FSFile::open(&path).map(|mut file| {
            file.read_to_string(&mut string)
                .map_err(|e| error!("Failed reading file: '{}'", path));
        });

        parser.read(string).map(|(header, data)| {
            self.new_file_from_parser_result(m, id.clone(), header, data);
        });

        self.load(&id)
    }

    pub fn new_file(&self, module: &Module)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: String::from(""),
            id: self.get_new_file_id(),
        };

        debug!("Create new File object: {:?}", &f);
        self.put_in_cache(f)
    }

    pub fn new_file_from_parser_result(&self,
                                       module: &Module,
                                       id: FileID,
                                       header: FileHeaderData,
                                       data: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: header,
            data: data,
            id: id,
        };
        debug!("Create new File object from parser result: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_header(&self,
                                module: &Module,
                                h: FileHeaderData)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: String::from(""),
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with header: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_data(&self, module: &Module, d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with data: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_content(&self,
                                 module: &Module,
                                 h: FileHeaderData,
                                 d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with content: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn persist<HP>(&self,
                       p: &Parser<HP>,
                       f: Rc<RefCell<File>>) -> bool
        where HP: FileHeaderParser
    {
        let file = f.deref().borrow();
        let text = p.write(file.contents());
        if text.is_err() {
            error!("Error: {}", text.err().unwrap());
            return false;
        }

        let path = {
            let ids : String = file.id().clone().into();
            format!("{}/{}-{}.imag", self.storepath, file.owning_module_name, ids)
        };

        self.ensure_store_path_exists();

        FSFile::create(&path).map(|mut fsfile| {
            fsfile.write_all(&text.unwrap().clone().into_bytes()[..])
        }).map_err(|writeerr|  {
            debug!("Could not create file at '{}'", path);
        }).and(Ok(true)).unwrap()
    }

    fn ensure_store_path_exists(&self) {
        use std::fs::create_dir_all;
        use std::process::exit;

        create_dir_all(&self.storepath).unwrap_or_else(|e| {
            error!("Could not create store: '{}'", self.storepath);
            error!("Error                 : '{}'", e);
            error!("Killing myself now");
            exit(1);
        })
    }

    pub fn load(&self, id: &FileID) -> Option<Rc<RefCell<File>>> {
        debug!("Loading '{:?}'", id);
        self.cache.borrow().get(id).cloned()
    }

    pub fn remove(&self, id: FileID) -> bool {
        use std::fs::remove_file;

        self.cache
            .borrow_mut()
            .remove(&id)
            .map(|file| {
                let idstr : String = id.into();
                let path = format!("{}/{}-{}.imag",
                                   self.storepath,
                                   file.deref().borrow().owner_name(),
                                   idstr);
                remove_file(path).is_ok()
            })
            .unwrap_or(false)
    }

    pub fn load_for_module<HP>(&self, m: &Module, parser: &Parser<HP>)
        -> Vec<Rc<RefCell<File>>>
        where HP: FileHeaderParser
    {
        use glob::{glob, Paths, PatternError};

        let globstr = format!("{}/{}-*.imag", self.storepath, m.name());
        let mut res = vec![];

        glob(&globstr[..]).map(|paths| {
            for path in paths {
                if let Ok(pathbuf) = path {
                    let fname = pathbuf.file_name().and_then(|s| s.to_str());
                    fname.map(|s| {
                        FileID::parse(&String::from(s)).map(|id| {
                            self.load_in_cache(m, parser, id).map(|file| {
                                res.push(file);
                            })
                        });
                    });
                }
            }
        });
        res
    }

    fn get_new_file_id(&self) -> FileID {
        use uuid::Uuid;
        let hash = FileHash::from(Uuid::new_v4().to_hyphenated_string());
        FileID::new(FileIDType::UUID, hash)
    }

}
<|endoftext|>


<commit_before><commit_msg>:sparkles: Make to possible create all project name by id<commit_after><|endoftext|>


<commit_before><commit_msg>Commiting wheel timer<commit_after>extern crate test;

use test::Bencher;

use std::fmt::{Show, Formatter, Result};
use std::iter::AdditiveIterator;

enum Node<T> {
  Cons(T, Box<Node<T>>),
  Nil
}

impl<T> Node<T> {
  fn new() -> Node<T> {
    Nil
  }

  fn prepend(self, elem: T) -> Node<T> {
    Cons(elem, box self)
  }

  fn len(&self) -> uint {
    match *self {
      Cons(_, ref tail) => tail.len() + 1,
      Nil => 0
    }
  }
}

impl<T: Show> Show for Node<T> {
  fn fmt(&self, f: &mut Formatter) -> Result {
    match *self {
      Cons(ref head, ref tail) => {
        write!(f, "{}, [ ] -> {}", head, tail)
      },
      Nil => {
        write!(f, "Nil")
      },
    }
  }
}

impl<T: PartialEq> PartialEq for Node<T> {
  fn eq(&self, ys: &Node<T>) -> bool {
    match (self, ys) {
      (&Nil, &Nil) => true,
      (&Cons(ref x, box ref next_xs), &Cons(ref y, box ref next_ys))
        if x == y => next_xs == next_ys,
      _ => false
    }
  }
}
// Simple hashed wheel timer with bounded interval
// See http://www.cs.columbia.edu/~nahum/w6998/papers/sosp87-timing-wheels.pdf
struct WheelTimer<T> {
  maxInterval: uint,
  currentTick: uint,

  ring: Vec<Node<T>>
}

impl<T> WheelTimer<T> {

  // Returns the number of items currently scheduled
  fn size(&self) -> uint {
    return self.ring.iter().map(|node| node.len()).sum()
  }

  // Creates a new timer with the specified max interval
  fn new(maxInterval: uint) -> WheelTimer<T> {
    // Initialize the ring with Nil values
    let mut ring = Vec::with_capacity(maxInterval);
    for _ in range(0u, maxInterval) {
      ring.push(Nil)
    }

    return WheelTimer{
      maxInterval: maxInterval,
      currentTick: 0,
      ring: ring
    }
  }

  // Schedules a new value, available after `ticks`
  fn schedule(&mut self, ticks: uint, value: T) {
    // Compute the scheduled position in the wheel
    let index = (self.currentTick + ticks) % self.maxInterval;

    // Get the current node at `index` in the wheel
    let node = std::mem::replace(self.ring.get_mut(index), Nil);

    // Set the position in the wheel with the appended node
    *self.ring.get_mut(index) = node.prepend(value);
  }

  // Tick the timer, returning the list of nodes at the spot
  fn tick(&mut self) -> Node<T> {
    // Get the node at the current tick in the wheel
    let node = std::mem::replace(self.ring.get_mut(self.currentTick), Nil);

    // Increment the timer
    self.currentTick = (self.currentTick + 1) % self.maxInterval;

    // Return the node that was in that spot
    return node
  }
}

fn main() {
  // LinkedList example
  // Create an empty linked list
  let mut list = Node::<uint>::new();

  // Append some elements
  list = list.prepend(1);
  list = list.prepend(2);
  list = list.prepend(3);

  // Show the final state of the list
  println!("linked list has length: {}", list.len());
  println!("{}", list);

  // WheelTimer example
  // Create a new timer
  let mut timer = WheelTimer::<uint>::new(3);

  // Schedule some things
  timer.schedule(1, 1);
  timer.schedule(2, 2);
  timer.schedule(3, 3);

  // Print the timer size
  println!("size: {}", timer.size());

  // Tick! Tick! Tick!
  println!("{}", timer.tick());
  println!("{}", timer.tick());
  println!("{}", timer.tick());
}

#[test]
fn wheel_timer_new_test() {
  let timer = WheelTimer::<uint>::new(3);
  assert!(timer.maxInterval == 3);
  assert!(timer.ring.capacity() == 3);
  assert!(timer.ring.len() == 3);
}

#[test]
fn wheel_timer_schedule_test() {
  let mut timer = WheelTimer::<&'static str>::new(10);
  timer.schedule(3, "tick");

  timer.tick();
  timer.tick();
  timer.tick();

  let node = timer.tick();
  assert!(node != Nil);

  let val = match node {
    Cons(val, _) => val,
    Nil => ""
  };
  assert!(val == "tick");
}

#[test]
fn wheel_timer_tick_test() {
  let mut timer = WheelTimer::<uint>::new(10);

  for i in range(0, 10) {
    timer.schedule(i, i)
  }

  for i in range(0, 10) {
    let node = timer.tick();
    assert!(node != Nil);

    let val = match node {
      Cons(val, _) => val,
      Nil => -1
    };
    assert!(val == i);
  }
}

#[bench]
fn bench_wheel_timer_drain(b: &mut Bencher) {
  let maxInterval = 20;
  let mut timer = WheelTimer::<uint>::new(maxInterval);

  b.iter(|| {
    // Fill
    for j in range(0u, 100u) {
      timer.schedule(j%maxInterval, j%maxInterval);
    }

    // Drain
    for _ in range(0u, 100u) {
      timer.tick();
    }
  });
}

#[bench]
fn bench_wheel_timer_fill(b: &mut Bencher) {
  let maxInterval = 20;
  let mut timer = WheelTimer::<uint>::new(maxInterval);
  let mut i = 0;

  b.iter(|| {
    timer.schedule(i%maxInterval, i%maxInterval);
    i = i + 1;
  });
}

#[bench]
fn bench_wheel_timer_fast(b: &mut Bencher) {
  let maxInterval = 2;
  let mut timer = WheelTimer::<uint>::new(maxInterval);
  let mut i = 0;

  b.iter(|| {
    timer.schedule(i%maxInterval, i%maxInterval);
    timer.tick();
    i = i + 1;
  });
}
<|endoftext|>


<commit_before><commit_msg>Get started with importing ethernet scheme to userspace<commit_after>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::{str, String, ToString};
use redox::to_num::*;
use redox::Vec;

/// Ethernet resource
pub struct Resource {
    /// The network
    network: Box<Resource>,
    /// The data
    data: Vec<u8>,
    /// The MAC addresss
    peer_addr: MACAddr,
    /// The ethernet type
    ethertype: u16,
}

impl Resource {
    fn dup(&self) -> Option<Box<Self>> {
        match self.network.dup() {
            Some(network) => Some(box Resource {
                network: network,
                data: self.data.clone(),
                peer_addr: self.peer_addr,
                ethertype: self.ethertype,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("ethernet://{}/{}", self.peer_addr.to_string(), String::from_num_radix(self.ethertype as usize, 16));

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
        if self.data.len() > 0 {
            let mut bytes: Vec<u8> = Vec::new();
            swap(&mut self.data, &mut bytes);
            vec.push_all(&bytes);
            return Some(bytes.len());
        }

        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.network.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                        if frame.header.ethertype.get() == self.ethertype &&
                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) &&
                           (frame.header.src.equals(self.peer_addr) ||
                            self.peer_addr.equals(BROADCAST_MAC_ADDR)) {
                            vec.push_all(&frame.data);
                            return Some(frame.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let data = Vec::from(buf);

        /*
        match self.network.write(EthernetII {
            header: EthernetIIHeader {
                src: unsafe { MAC_ADDR },
                dst: self.peer_addr,
                ethertype: n16::new(self.ethertype),
            },
            data: data,
        }.to_bytes().as_slice()) {
            Some(_) => return Some(buf.len()),
            None => return None,
        }
        */
        None
    }

    fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    fn sync(&mut self) -> bool {
        self.network.sync()
    }
}

pub struct Scheme;

impl Scheme {
    fn new() -> Box<Self> {
        box Scheme
    }

    fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        //Split scheme from the rest of the URL
        let (scheme, mut not_scheme) = url.split_at(url.find(':').unwrap_or(url.len()));

        //Remove the starting two slashes
        if not_scheme.starts_with("//") {
            not_scheme = &not_scheme[2..not_scheme.len() - 2];
        }

        //Check host and port vs path
        if not_scheme.starts_with("/") {
            if let Some(mut network) = File::open("network://") {
                if url.path().len() > 0 {
                    let ethertype = url.path().to_num_radix(16) as u16;

                    if url.host().len() > 0 {
                        return Some(box Resource {
                            network: network,
                            data: Vec::new(),
                            peer_addr: MACAddr::from_string(&url.host()),
                            ethertype: ethertype,
                        });
                    } else {
                        loop {
                            let mut bytes: Vec<u8> = Vec::new();
                            match network.read_to_end(&mut bytes) {
                                Some(_) => {
                                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                                        if frame.header.ethertype.get() == ethertype &&
                                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) {
                                            return Some(box Resource {
                                                network: network,
                                                data: frame.data,
                                                peer_addr: frame.header.src,
                                                ethertype: ethertype,
                                            });
                                        }
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                } else {
                    /*
                    debug::d("Ethernet: No ethertype provided\n");
                    */
                }
            }
        }

        None
    }
}
<|endoftext|>


<commit_before><commit_msg>Move two AbsoluteBoxOffsets fields into a Vec2<commit_after><|endoftext|>


<commit_before>use runtime::Runtime;
use std::error::Error;
use std::fmt::Formatter;
use std::fmt::Result as FMTResult;
use std::fmt::Display;
use std::result::Result;
use std::collections::HashMap;

use clap::{App, ArgMatches};

use storage::backend::{StorageBackend, StorageBackendError};

pub mod bm;

#[derive(Debug)]
pub struct ModuleError {
    desc: String,
    caused_by: Option<Box<Error>>,
}

impl ModuleError {
    pub fn new(desc: &'static str) -> ModuleError {
        ModuleError {
            desc: desc.to_owned().to_string(),
            caused_by: None,
        }
    }
}

impl Error for ModuleError {

    fn description(&self) -> &str {
        &self.desc[..]
    }

    fn cause(&self) -> Option<&Error> {
        self.caused_by.as_ref().map(|e| &**e)
    }

}

impl Display for ModuleError {
    fn fmt(&self, f: &mut Formatter) -> FMTResult {
        write!(f, "ModuleError: {}", self.description())
    }
}

pub struct CommandEnv<'a> {
    pub rt:         &'a Runtime<'a>,
    pub bk:         &'a StorageBackend,
    pub matches:    &'a ArgMatches<'a, 'a>,
}

pub type ModuleResult = Result<(), ModuleError>;
pub type CommandResult  = ModuleResult;
pub type CommandMap<'a> = HashMap<&'a str, fn(&Module, CommandEnv) -> CommandResult>;

pub trait Module {

    fn callnames(&self) -> &'static [&'static str];
    fn name(&self) -> &'static str;
    fn shutdown(&self, rt : &Runtime) -> ModuleResult;

    fn get_commands(&self, rt: &Runtime) -> CommandMap;

}

<commit_msg>Rewrite Debug for Module<commit_after>use runtime::Runtime;
use std::error::Error;
use std::fmt::Formatter;
use std::fmt::Result as FMTResult;
use std::fmt::Display;
use std::fmt::Debug;
use std::path::Path;
use std::result::Result;
use std::collections::HashMap;

use clap::{App, ArgMatches};

use storage::backend::{StorageBackend, StorageBackendError};

pub mod bm;

#[derive(Debug)]
pub struct ModuleError {
    desc: String,
    caused_by: Option<Box<Error>>,
}

impl ModuleError {
    pub fn new(desc: &'static str) -> ModuleError {
        ModuleError {
            desc: desc.to_owned().to_string(),
            caused_by: None,
        }
    }
}

impl Error for ModuleError {

    fn description(&self) -> &str {
        &self.desc[..]
    }

    fn cause(&self) -> Option<&Error> {
        self.caused_by.as_ref().map(|e| &**e)
    }

}

impl Display for ModuleError {
    fn fmt(&self, f: &mut Formatter) -> FMTResult {
        write!(f, "ModuleError: {}", self.description())
    }
}

pub struct CommandEnv<'a> {
    pub rt:         &'a Runtime<'a>,
    pub bk:         &'a StorageBackend,
    pub matches:    &'a ArgMatches<'a, 'a>,
}

pub type ModuleResult = Result<(), ModuleError>;
pub type CommandResult  = ModuleResult;
pub type CommandMap<'a> = HashMap<&'a str, fn(&Module, CommandEnv) -> CommandResult>;

pub trait Module : Debug {

    fn callnames(&self) -> &'static [&'static str];
    fn name(&self) -> &'static str;
    fn shutdown(&self, rt : &Runtime) -> ModuleResult;

    fn get_commands(&self, rt: &Runtime) -> CommandMap;

}

<|endoftext|>


<commit_before><commit_msg>Remove tests for ruma_common types, they now live in that crate<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the Vulkan instance extensions, which moves the renderer initialisation on further, on Windows at least<commit_after><|endoftext|>


<commit_before><commit_msg>[impl] Add a simple example showing the various options<commit_after>extern crate hexplay;

use hexplay::*;

fn main() {
    let data: Vec<u8> = (0u16..256u16).map(|v| v as u8).collect();

    let default_view = HexViewBuilder::new(&data)
        .finish();
    println!("Default view of all data:\n{}\n\n", default_view);

    let ascii_view = HexViewBuilder::new(&data)
        .codepage(CODEPAGE_ASCII)
        .finish();
    println!("Ascii codepage view of all data:\n{}\n\n", ascii_view);

    let partial_view = HexViewBuilder::new(&data[10..80])
        .address_offset(10)
        .finish();
    println!("Default view of a subslice:\n{}\n\n", partial_view);

    let narrowed_view = HexViewBuilder::new(&data)
        .row_width(10)
        .finish();
    println!("Narrowed view of all data:\n{}\n\n", narrowed_view);

    let combined_view = HexViewBuilder::new(&data[10..180])
        .address_offset(10)
        .codepage(CODEPAGE_1252)
        .row_width(14)
        .finish();
    println!("Custom view: \n{}\n\n", combined_view);
}
<|endoftext|>


<commit_before><commit_msg>Started on example<commit_after>extern crate dynamic_reload;

fn main() {

}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2379<commit_after>// https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/
pub fn minimum_recolors(blocks: String, k: i32) -> i32 {
    todo!()
}

fn main() {
    println!("{}", minimum_recolors("WBBWWBBWBW".to_string(), 7)); // 3
    println!("{}", minimum_recolors("WBWBBBW".to_string(), 2)); // 0
}
<|endoftext|>


<commit_before><commit_msg>Get started with importing the ip scheme to userspace<commit_after>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::str;
use redox::{String, ToString};
use redox::to_num::*;
use redox::Vec;

/// IP resource
pub struct Resource {
    link: Box<Resource>,
    data: Vec<u8>,
    peer_addr: IPv4Addr,
    proto: u8,
    id: u16,
}

impl Resource {
    pub fn dup(&self) -> Option<Box<Self>> {
        match self.link.dup() {
            Some(link) => Some(box IPResource {
                link: link,
                data: self.data.clone(),
                peer_addr: self.peer_addr,
                proto: self.proto,
                id: self.id,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("ip://{}{}/{}", self.peer_addr.to_string(), String::from_num_radix(self.proto as usize, 16));

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
           if self.data.len() > 0 {
            let mut bytes: Vec<u8> = Vec::new();
            mem::swap(&mut self.data, &mut bytes);
            vec.push_all(&bytes);
            return Some(bytes.len());
        }

        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.link.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(packet) = IPv4::from_bytes(bytes) {
                        if packet.header.proto == self.proto && packet.header.dst.equals(IP_ADDR) &&
                           packet.header.src.equals(self.peer_addr) {
                            vec.push_all(&packet.data);
                            return Some(packet.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let ip_data = Vec::from(buf);

        self.id += 1;
        let mut ip = IPv4 {
            header: IPv4Header {
                ver_hlen: 0x40 | (mem::size_of::<IPv4Header>()/4 & 0xF) as u8, // No Options
                services: 0,
                len: n16::new((mem::size_of::<IPv4Header>() + ip_data.len()) as u16), // No Options
                id: n16::new(self.id),
                flags_fragment: n16::new(0),
                ttl: 128,
                proto: self.proto,
                checksum: Checksum { data: 0 },
                src: IP_ADDR,
                dst: self.peer_addr,
            },
            options: Vec::new(),
            data: ip_data,
        };

        unsafe {
            let header_ptr: *const IPv4Header = &ip.header;
            ip.header.checksum.data =
                Checksum::compile(Checksum::sum(header_ptr as usize, mem::size_of::<IPv4Header>()) +
                                  Checksum::sum(ip.options.as_ptr() as usize, ip.options.len()));
        }

        match self.link.write(ip.to_bytes().as_slice()) {
            Some(_) => return Some(buf.len()),
            None => return None,
        }
    }

    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    pub fn sync(&mut self) -> bool {
        self.link.sync()
    }
}

/// A ARP entry (MAC + IP)
pub struct ARPEntry {
    ip: IPv4Addr,
    mac: MACAddr,
}

/// IP scheme
pub struct Scheme {
    pub arp: Vec<ARPEntry>,
}

impl Scheme {
    pub fn new() -> Box<Self> {
        box Scheme
    }

    pub fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        if url.path().len() > 0 {
            let proto = url.path().to_num_radix(16) as u8;

            if url.host().len() > 0 {
                let peer_addr = IPv4Addr::from_string(&url.host());
                let mut peer_mac = BROADCAST_MAC_ADDR;

                for entry in self.arp.iter() {
                    if entry.ip.equals(peer_addr) {
                        peer_mac = entry.mac;
                        break;
                    }
                }

                if peer_mac.equals(BROADCAST_MAC_ADDR) {
                    if let Some(mut link) = URL::from_string(&("ethernet://".to_string() + peer_mac.to_string() + "/806")).open() {
                        let arp = ARP {
                            header: ARPHeader {
                                htype: n16::new(1),
                                ptype: n16::new(0x800),
                                hlen: 6,
                                plen: 4,
                                oper: n16::new(1),
                                src_mac: unsafe { MAC_ADDR },
                                src_ip: IP_ADDR,
                                dst_mac: peer_mac,
                                dst_ip: peer_addr,
                            },
                            data: Vec::new(),
                        };

                        match link.write(arp.to_bytes().as_slice()) {
                            Some(_) => loop {
                                let mut bytes: Vec<u8> = Vec::new();
                                match link.read_to_end(&mut bytes) {
                                    Some(_) =>
                                        if let Some(packet) = ARP::from_bytes(bytes) {
                                        if packet.header.oper.get() == 2 &&
                                           packet.header.src_ip.equals(peer_addr) {
                                            peer_mac = packet.header.src_mac;
                                            self.arp.push(ARPEntry {
                                                ip: peer_addr,
                                                mac: peer_mac,
                                            });
                                            break;
                                        }
                                    },
                                    None => (),
                                }
                            },
                            None => debug::d("IP: ARP Write Failed!\n"),
                        }
                    }
                }

                if let Some(link) = URL::from_string(&("ethernet://".to_string() + peer_mac.to_string() + "/800")).open() {
                    return Some(box IPResource {
                        link: link,
                        data: Vec::new(),
                        peer_addr: peer_addr,
                        proto: proto,
                        id: (rand() % 65536) as u16,
                    });
                }
            } else {
                while let Some(mut link) = URL::from_str("ethernet:///800").open() {
                    let mut bytes: Vec<u8> = Vec::new();
                    match link.read_to_end(&mut bytes) {
                        Some(_) => {
                            if let Some(packet) = IPv4::from_bytes(bytes) {
                                if packet.header.proto == proto &&
                                   packet.header.dst.equals(IP_ADDR) {
                                    return Some(box IPResource {
                                        link: link,
                                        data: packet.data,
                                        peer_addr: packet.header.src,
                                        proto: proto,
                                        id: (rand() % 65536) as u16,
                                    });
                                }
                            }
                        }
                        None => break,
                    }
                }
            }
        } else {
            /*
            debug::d("IP: No protocol provided\n");
            */
        }

        None
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #24828 - jooert:fix23253, r=pnkfelix<commit_after>// Copyright 2014 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.

enum Foo { Bar }

fn main() {
    Foo::Bar.a;
    //~^ ERROR: attempted access of field `a` on type `Foo`, but no field with that name was found
}
<|endoftext|>


<commit_before><commit_msg>Change HabitInstance implementation to not contain comment in instance<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! A windowing implementation using GLUT.

use windowing::{ApplicationMethods, WindowEvent, WindowMethods};
use windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use windowing::{Forward, Back};

use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::local_data;
use std::rc::Rc;
use geom::point::Point2D;
use geom::size::Size2D;
use servo_msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use servo_msg::compositor_msg::{FinishedLoading, Blank, ReadyState};

use glut::glut::{ACTIVE_SHIFT, DOUBLE, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;

// static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];

/// A structure responsible for setting up and tearing down the entire windowing system.
pub struct Application;

impl ApplicationMethods for Application {
    fn new() -> Application {
        glut::init();
        glut::init_display_mode(DOUBLE);
        Application
    }
}

impl Drop for Application {
    fn drop(&mut self) {
        drop_local_window();
    }
}

/// The type of a window.
pub struct Window {
    pub glut_window: glut::Window,

    pub event_queue: RefCell<~[WindowEvent]>,

    pub drag_origin: Point2D<c_int>,

    pub mouse_down_button: Cell<c_int>,
    pub mouse_down_point: Cell<Point2D<c_int>>,

    pub ready_state: Cell<ReadyState>,
    pub render_state: Cell<RenderState>,
    pub throbber_frame: Cell<u8>,
}

impl WindowMethods<Application> for Window {
    /// Creates a new window.
    fn new(_: &Application) -> Rc<Window> {
        // Create the GLUT window.
        glut::init_window_size(800, 600);
        let glut_window = glut::create_window("Servo".to_owned());

        // Create our window object.
        let window = Window {
            glut_window: glut_window,

            event_queue: RefCell::new(~[]),

            drag_origin: Point2D(0 as c_int, 0),

            mouse_down_button: Cell::new(0),
            mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),

            ready_state: Cell::new(Blank),
            render_state: Cell::new(IdleRenderState),
            throbber_frame: Cell::new(0),
        };

        // Register event handlers.

        //Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.

        struct DisplayCallbackState;
        impl glut::DisplayCallback for DisplayCallbackState {
            fn call(&self) {
                debug!("GLUT display func registgered");
            }
        }
        glut::display_func(~DisplayCallbackState);
        struct ReshapeCallbackState;
        impl glut::ReshapeCallback for ReshapeCallbackState {
            fn call(&self, width: c_int, height: c_int) {
                let tmp = local_window();
                tmp.event_queue.borrow_mut().push(ResizeWindowEvent(width as uint, height as uint))
            }
        }
        glut::reshape_func(glut_window, ~ReshapeCallbackState);
        struct KeyboardCallbackState;
        impl glut::KeyboardCallback for KeyboardCallbackState {
            fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
                let tmp = local_window();
                tmp.handle_key(key)
            }
        }
        glut::keyboard_func(~KeyboardCallbackState);
        struct MouseCallbackState;
        impl glut::MouseCallback for MouseCallbackState {
            fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
                if button < 3 {
                    let tmp = local_window();
                    tmp.handle_mouse(button, state, x, y);
                } else {
                    match button {
                        3 => {
                            let tmp = local_window();
                            tmp.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, 5.0 as f32), Point2D(0.0 as i32, 5.0 as i32)));
                        },
                        4 => {
                            let tmp = local_window();
                            tmp.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, -5.0 as f32), Point2D(0.0 as i32, -5.0 as i32)));
                        },
                        _ => {}
                    }
                }
            }
        }
        glut::mouse_func(~MouseCallbackState);

        let wrapped_window = Rc::new(window);

        install_local_window(wrapped_window.clone());

        wrapped_window
    }

    /// Returns the size of the window.
    fn size(&self) -> Size2D<f32> {
        Size2D(glut::get(WindowWidth) as f32, glut::get(WindowHeight) as f32)
    }

    /// Presents the window to the screen (perhaps by page flipping).
    fn present(&self) {
        glut::swap_buffers();
    }

    fn recv(&self) -> WindowEvent {
        if !self.event_queue.borrow_mut().is_empty() {
            return self.event_queue.borrow_mut().shift().unwrap();
        }

        glut::check_loop();

        self.event_queue.borrow_mut().shift().unwrap_or(IdleWindowEvent)
    }

    /// Sets the ready state.
    fn set_ready_state(&self, ready_state: ReadyState) {
        self.ready_state.set(ready_state);
        //FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
        //self.update_window_title()
    }

    /// Sets the render state.
    fn set_render_state(&self, render_state: RenderState) {
        if self.ready_state.get() == FinishedLoading &&
            self.render_state.get() == RenderingRenderState &&
            render_state == IdleRenderState {
            // page loaded
            self.event_queue.borrow_mut().push(FinishedWindowEvent);
        }

        self.render_state.set(render_state);
        //FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
        //self.update_window_title()
    }

    fn hidpi_factor(&self) -> f32 {
        //FIXME: Do nothing in GLUT now.
    0f32
    }
}

impl Window {
    /// Helper function to set the window title in accordance with the ready state.
    // fn update_window_title(&self) {
    //     let throbber = THROBBER[self.throbber_frame];
    //     match self.ready_state {
    //         Blank => {
    //             glut::set_window_title(self.glut_window, "Blank")
    //         }
    //         Loading => {
    //             glut::set_window_title(self.glut_window, format!("{:c} Loading . Servo", throbber))
    //         }
    //         PerformingLayout => {
    //             glut::set_window_title(self.glut_window, format!("{:c} Performing Layout . Servo", throbber))
    //         }
    //         FinishedLoading => {
    //             match self.render_state {
    //                 RenderingRenderState => {
    //                     glut::set_window_title(self.glut_window, format!("{:c} Rendering . Servo", throbber))
    //                 }
    //                 IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
    //             }
    //         }
    //     }
    // }

    /// Helper function to handle keyboard events.
    fn handle_key(&self, key: u8) {
        debug!("got key: {}", key);
        let modifiers = glut::get_modifiers();
        match key {
            42 => self.load_url(),
            43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
            45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
            56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, 5.0 as f32), Point2D(0.0 as i32, 5.0 as i32))),
            50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, -5.0 as f32), Point2D(0.0 as i32, -5.0 as i32))),
            127 => {
                if (modifiers & ACTIVE_SHIFT) != 0 {
                    self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
                }
                else {
                    self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
                }
            }
            _ => {}
        }
    }

    /// Helper function to handle a click
    fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
        // FIXME(tkuehn): max pixel dist should be based on pixel density
        let max_pixel_dist = 10f32;
        let event = match state {
            glut::MOUSE_DOWN => {
                self.mouse_down_point.set(Point2D(x, y));
                self.mouse_down_button.set(button);
                MouseWindowMouseDownEvent(button as uint, Point2D(x as f32, y as f32))
            }
            glut::MOUSE_UP => {
                if self.mouse_down_button.get() == button {
                    let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
                    let pixel_dist = ((pixel_dist.x * pixel_dist.x +
                                       pixel_dist.y * pixel_dist.y) as f32).sqrt();
                    if pixel_dist < max_pixel_dist {
                        let click_event = MouseWindowClickEvent(button as uint,
                                                           Point2D(x as f32, y as f32));
                        self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
                    }
                }
                MouseWindowMouseUpEvent(button as uint, Point2D(x as f32, y as f32))
            }
            _ => fail!("I cannot recognize the type of mouse action that occured. :-(")
        };
        self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
    }

    /// Helper function to pop up an alert box prompting the user to load a URL.
    fn load_url(&self) {
        let mut alert: Alert = AlertMethods::new("Navigate to:");
        alert.add_prompt();
        alert.run();
        let value = alert.prompt_value();
        if "" == value {    // To avoid crashing on Linux.
            self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_owned()))
        } else {
            self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
        }
    }
}

static TLS_KEY: local_data::Key<Rc<Window>> = &local_data::Key;

fn install_local_window(window: Rc<Window>) {
    local_data::set(TLS_KEY, window);
}

fn drop_local_window() {
    local_data::pop(TLS_KEY);
}

fn local_window() -> Rc<Window> {
    local_data::get(TLS_KEY, |v| v.unwrap().clone())
}
<commit_msg>~[] to Vec in glut_windowing<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! A windowing implementation using GLUT.

use windowing::{ApplicationMethods, WindowEvent, WindowMethods};
use windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use windowing::{Forward, Back};

use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::local_data;
use std::rc::Rc;
use geom::point::Point2D;
use geom::size::Size2D;
use servo_msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use servo_msg::compositor_msg::{FinishedLoading, Blank, ReadyState};

use glut::glut::{ACTIVE_SHIFT, DOUBLE, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;

// static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];

/// A structure responsible for setting up and tearing down the entire windowing system.
pub struct Application;

impl ApplicationMethods for Application {
    fn new() -> Application {
        glut::init();
        glut::init_display_mode(DOUBLE);
        Application
    }
}

impl Drop for Application {
    fn drop(&mut self) {
        drop_local_window();
    }
}

/// The type of a window.
pub struct Window {
    pub glut_window: glut::Window,

    pub event_queue: RefCell<Vec<WindowEvent>>,

    pub drag_origin: Point2D<c_int>,

    pub mouse_down_button: Cell<c_int>,
    pub mouse_down_point: Cell<Point2D<c_int>>,

    pub ready_state: Cell<ReadyState>,
    pub render_state: Cell<RenderState>,
    pub throbber_frame: Cell<u8>,
}

impl WindowMethods<Application> for Window {
    /// Creates a new window.
    fn new(_: &Application) -> Rc<Window> {
        // Create the GLUT window.
        glut::init_window_size(800, 600);
        let glut_window = glut::create_window("Servo".to_owned());

        // Create our window object.
        let window = Window {
            glut_window: glut_window,

            event_queue: RefCell::new(Vec::new()),

            drag_origin: Point2D(0 as c_int, 0),

            mouse_down_button: Cell::new(0),
            mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),

            ready_state: Cell::new(Blank),
            render_state: Cell::new(IdleRenderState),
            throbber_frame: Cell::new(0),
        };

        // Register event handlers.

        //Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.

        struct DisplayCallbackState;
        impl glut::DisplayCallback for DisplayCallbackState {
            fn call(&self) {
                debug!("GLUT display func registgered");
            }
        }
        glut::display_func(~DisplayCallbackState);
        struct ReshapeCallbackState;
        impl glut::ReshapeCallback for ReshapeCallbackState {
            fn call(&self, width: c_int, height: c_int) {
                let tmp = local_window();
                tmp.event_queue.borrow_mut().push(ResizeWindowEvent(width as uint, height as uint))
            }
        }
        glut::reshape_func(glut_window, ~ReshapeCallbackState);
        struct KeyboardCallbackState;
        impl glut::KeyboardCallback for KeyboardCallbackState {
            fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
                let tmp = local_window();
                tmp.handle_key(key)
            }
        }
        glut::keyboard_func(~KeyboardCallbackState);
        struct MouseCallbackState;
        impl glut::MouseCallback for MouseCallbackState {
            fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
                if button < 3 {
                    let tmp = local_window();
                    tmp.handle_mouse(button, state, x, y);
                } else {
                    match button {
                        3 => {
                            let tmp = local_window();
                            tmp.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, 5.0 as f32), Point2D(0.0 as i32, 5.0 as i32)));
                        },
                        4 => {
                            let tmp = local_window();
                            tmp.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, -5.0 as f32), Point2D(0.0 as i32, -5.0 as i32)));
                        },
                        _ => {}
                    }
                }
            }
        }
        glut::mouse_func(~MouseCallbackState);

        let wrapped_window = Rc::new(window);

        install_local_window(wrapped_window.clone());

        wrapped_window
    }

    /// Returns the size of the window.
    fn size(&self) -> Size2D<f32> {
        Size2D(glut::get(WindowWidth) as f32, glut::get(WindowHeight) as f32)
    }

    /// Presents the window to the screen (perhaps by page flipping).
    fn present(&self) {
        glut::swap_buffers();
    }

    fn recv(&self) -> WindowEvent {
        if !self.event_queue.borrow_mut().is_empty() {
            return self.event_queue.borrow_mut().shift().unwrap();
        }

        glut::check_loop();

        self.event_queue.borrow_mut().shift().unwrap_or(IdleWindowEvent)
    }

    /// Sets the ready state.
    fn set_ready_state(&self, ready_state: ReadyState) {
        self.ready_state.set(ready_state);
        //FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
        //self.update_window_title()
    }

    /// Sets the render state.
    fn set_render_state(&self, render_state: RenderState) {
        if self.ready_state.get() == FinishedLoading &&
            self.render_state.get() == RenderingRenderState &&
            render_state == IdleRenderState {
            // page loaded
            self.event_queue.borrow_mut().push(FinishedWindowEvent);
        }

        self.render_state.set(render_state);
        //FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
        //self.update_window_title()
    }

    fn hidpi_factor(&self) -> f32 {
        //FIXME: Do nothing in GLUT now.
    0f32
    }
}

impl Window {
    /// Helper function to set the window title in accordance with the ready state.
    // fn update_window_title(&self) {
    //     let throbber = THROBBER[self.throbber_frame];
    //     match self.ready_state {
    //         Blank => {
    //             glut::set_window_title(self.glut_window, "Blank")
    //         }
    //         Loading => {
    //             glut::set_window_title(self.glut_window, format!("{:c} Loading . Servo", throbber))
    //         }
    //         PerformingLayout => {
    //             glut::set_window_title(self.glut_window, format!("{:c} Performing Layout . Servo", throbber))
    //         }
    //         FinishedLoading => {
    //             match self.render_state {
    //                 RenderingRenderState => {
    //                     glut::set_window_title(self.glut_window, format!("{:c} Rendering . Servo", throbber))
    //                 }
    //                 IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
    //             }
    //         }
    //     }
    // }

    /// Helper function to handle keyboard events.
    fn handle_key(&self, key: u8) {
        debug!("got key: {}", key);
        let modifiers = glut::get_modifiers();
        match key {
            42 => self.load_url(),
            43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
            45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
            56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, 5.0 as f32), Point2D(0.0 as i32, 5.0 as i32))),
            50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(Point2D(0.0, -5.0 as f32), Point2D(0.0 as i32, -5.0 as i32))),
            127 => {
                if (modifiers & ACTIVE_SHIFT) != 0 {
                    self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
                }
                else {
                    self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
                }
            }
            _ => {}
        }
    }

    /// Helper function to handle a click
    fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
        // FIXME(tkuehn): max pixel dist should be based on pixel density
        let max_pixel_dist = 10f32;
        let event = match state {
            glut::MOUSE_DOWN => {
                self.mouse_down_point.set(Point2D(x, y));
                self.mouse_down_button.set(button);
                MouseWindowMouseDownEvent(button as uint, Point2D(x as f32, y as f32))
            }
            glut::MOUSE_UP => {
                if self.mouse_down_button.get() == button {
                    let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
                    let pixel_dist = ((pixel_dist.x * pixel_dist.x +
                                       pixel_dist.y * pixel_dist.y) as f32).sqrt();
                    if pixel_dist < max_pixel_dist {
                        let click_event = MouseWindowClickEvent(button as uint,
                                                           Point2D(x as f32, y as f32));
                        self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
                    }
                }
                MouseWindowMouseUpEvent(button as uint, Point2D(x as f32, y as f32))
            }
            _ => fail!("I cannot recognize the type of mouse action that occured. :-(")
        };
        self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
    }

    /// Helper function to pop up an alert box prompting the user to load a URL.
    fn load_url(&self) {
        let mut alert: Alert = AlertMethods::new("Navigate to:");
        alert.add_prompt();
        alert.run();
        let value = alert.prompt_value();
        if "" == value {    // To avoid crashing on Linux.
            self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_owned()))
        } else {
            self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
        }
    }
}

static TLS_KEY: local_data::Key<Rc<Window>> = &local_data::Key;

fn install_local_window(window: Rc<Window>) {
    local_data::set(TLS_KEY, window);
}

fn drop_local_window() {
    local_data::pop(TLS_KEY);
}

fn local_window() -> Rc<Window> {
    local_data::get(TLS_KEY, |v| v.unwrap().clone())
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #49781 - Robbepop:master, r=nikomatsakis<commit_after>// Copyright 2018 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.

// Regression test for #16223: without NLL the `if let` construct together with
// the nested box-structure of `Root` causes an unwanted collateral move.

// The exact error prevented here is:
//
// error[E0382]: use of collaterally moved value: `(root.boxed.rhs as SomeVariant::B).0`
//   --> src/main.rs:55:29
//    |
// 56 |         lhs: SomeVariant::A(a),
//    |                             - value moved here
// 57 |         rhs: SomeVariant::B(b),
//    |                             ^ value used here after move
//    |
//    = note: move occurs because the value has type `A`, which does not implement the `Copy` trait

// must-compile-successfully

#![feature(nll)]
#![feature(box_patterns)]

struct Root {
    boxed: Box<SetOfVariants>,
}

struct SetOfVariants {
    lhs: SomeVariant,
    rhs: SomeVariant,
}

enum SomeVariant {
    A(A),
    B(B),
}

struct A(String);
struct B(String);

fn main() {
    let root = Root {
        boxed: Box::new(SetOfVariants {
            lhs: SomeVariant::A(A(String::from("This is A"))),
            rhs: SomeVariant::B(B(String::from("This is B"))),
        }),
    };
    if let box SetOfVariants {
        lhs: SomeVariant::A(a),
        rhs: SomeVariant::B(b),
    } = root.boxed
    {
        println!("a = {}", a.0);
        println!("b = {}", b.0);
    }
}
<|endoftext|>


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

//! Tidy check to ensure that unstable features are all in order
//!
//! This check will ensure properties like:
//!
//! * All stability attributes look reasonably well formed
//! * The set of library features is disjoint from the set of language features
//! * Library features have at most one stability level
//! * Library features have at most one `since` value

use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

#[derive(PartialEq)]
enum Status {
    Stable,
    Unstable,
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let as_str = match *self {
            Status::Stable => "stable",
            Status::Unstable => "unstable",
        };
        fmt::Display::fmt(as_str, f)
    }
}

struct Feature {
    name: String,
    level: Status,
    since: String,
}

struct LibFeature {
    level: Status,
    since: String,
}

pub fn check(path: &Path, bad: &mut bool) {
    let features = collect_lang_features(&path.join("libsyntax/feature_gate.rs"));
    assert!(!features.is_empty());
    let mut lib_features = HashMap::<String, LibFeature>::new();

    let mut contents = String::new();
    super::walk(path,
                &mut |path| super::filter_dirs(path) || path.ends_with("src/test"),
                &mut |file| {
        let filename = file.file_name().unwrap().to_string_lossy();
        if !filename.ends_with(".rs") || filename == "features.rs" ||
           filename == "diagnostic_list.rs" {
            return;
        }

        contents.truncate(0);
        t!(t!(File::open(file)).read_to_string(&mut contents));

        for (i, line) in contents.lines().enumerate() {
            let mut err = |msg: &str| {
                println!("{}:{}: {}", file.display(), i + 1, msg);
                *bad = true;
            };
            let level = if line.contains("[unstable(") {
                Status::Unstable
            } else if line.contains("[stable(") {
                Status::Stable
            } else {
                continue;
            };
            let feature_name = match find_attr_val(line, "feature") {
                Some(name) => name,
                None => {
                    err("malformed stability attribute");
                    continue;
                }
            };
            let since = match find_attr_val(line, "since") {
                Some(name) => name,
                None if level == Status::Stable => {
                    err("malformed stability attribute");
                    continue;
                }
                None => "None",
            };

            if features.iter().any(|f| f.name == feature_name) {
                err("duplicating a lang feature");
            }
            if let Some(ref s) = lib_features.get(feature_name) {
                if s.level != level {
                    err("different stability level than before");
                }
                if s.since != since {
                    err("different `since` than before");
                }
                continue;
            }
            lib_features.insert(feature_name.to_owned(),
                                LibFeature {
                                    level: level,
                                    since: since.to_owned(),
                                });
        }
    });

    if *bad {
        return;
    }

    let mut lines = Vec::new();
    for feature in features {
        lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
                           feature.name,
                           "lang",
                           feature.level,
                           feature.since));
    }
    for (name, feature) in lib_features {
        lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
                           name,
                           "lib",
                           feature.level,
                           feature.since));
    }

    lines.sort();
    for line in lines {
        println!("* {}", line);
    }
}

fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
    line.find(attr)
        .and_then(|i| line[i..].find('"').map(|j| i + j + 1))
        .and_then(|i| line[i..].find('"').map(|j| (i, i + j)))
        .map(|(i, j)| &line[i..j])
}

fn collect_lang_features(path: &Path) -> Vec<Feature> {
    let mut contents = String::new();
    t!(t!(File::open(path)).read_to_string(&mut contents));

    contents.lines()
        .filter_map(|line| {
            let mut parts = line.trim().split(",");
            let level = match parts.next().map(|l| l.trim().trim_left_matches('(')) {
                Some("active") => Status::Unstable,
                Some("removed") => Status::Unstable,
                Some("accepted") => Status::Stable,
                _ => return None,
            };
            let name = parts.next().unwrap().trim();
            let since = parts.next().unwrap().trim().trim_matches('"');
            Some(Feature {
                name: name.to_owned(),
                level: level,
                since: since.to_owned(),
            })
        })
        .collect()
}
<commit_msg>tidy features: use 2-parameter form of internal try macro for open err<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Tidy check to ensure that unstable features are all in order
//!
//! This check will ensure properties like:
//!
//! * All stability attributes look reasonably well formed
//! * The set of library features is disjoint from the set of language features
//! * Library features have at most one stability level
//! * Library features have at most one `since` value

use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

#[derive(PartialEq)]
enum Status {
    Stable,
    Unstable,
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let as_str = match *self {
            Status::Stable => "stable",
            Status::Unstable => "unstable",
        };
        fmt::Display::fmt(as_str, f)
    }
}

struct Feature {
    name: String,
    level: Status,
    since: String,
}

struct LibFeature {
    level: Status,
    since: String,
}

pub fn check(path: &Path, bad: &mut bool) {
    let features = collect_lang_features(&path.join("libsyntax/feature_gate.rs"));
    assert!(!features.is_empty());
    let mut lib_features = HashMap::<String, LibFeature>::new();

    let mut contents = String::new();
    super::walk(path,
                &mut |path| super::filter_dirs(path) || path.ends_with("src/test"),
                &mut |file| {
        let filename = file.file_name().unwrap().to_string_lossy();
        if !filename.ends_with(".rs") || filename == "features.rs" ||
           filename == "diagnostic_list.rs" {
            return;
        }

        contents.truncate(0);
        t!(t!(File::open(&file), &file).read_to_string(&mut contents));

        for (i, line) in contents.lines().enumerate() {
            let mut err = |msg: &str| {
                println!("{}:{}: {}", file.display(), i + 1, msg);
                *bad = true;
            };
            let level = if line.contains("[unstable(") {
                Status::Unstable
            } else if line.contains("[stable(") {
                Status::Stable
            } else {
                continue;
            };
            let feature_name = match find_attr_val(line, "feature") {
                Some(name) => name,
                None => {
                    err("malformed stability attribute");
                    continue;
                }
            };
            let since = match find_attr_val(line, "since") {
                Some(name) => name,
                None if level == Status::Stable => {
                    err("malformed stability attribute");
                    continue;
                }
                None => "None",
            };

            if features.iter().any(|f| f.name == feature_name) {
                err("duplicating a lang feature");
            }
            if let Some(ref s) = lib_features.get(feature_name) {
                if s.level != level {
                    err("different stability level than before");
                }
                if s.since != since {
                    err("different `since` than before");
                }
                continue;
            }
            lib_features.insert(feature_name.to_owned(),
                                LibFeature {
                                    level: level,
                                    since: since.to_owned(),
                                });
        }
    });

    if *bad {
        return;
    }

    let mut lines = Vec::new();
    for feature in features {
        lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
                           feature.name,
                           "lang",
                           feature.level,
                           feature.since));
    }
    for (name, feature) in lib_features {
        lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
                           name,
                           "lib",
                           feature.level,
                           feature.since));
    }

    lines.sort();
    for line in lines {
        println!("* {}", line);
    }
}

fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
    line.find(attr)
        .and_then(|i| line[i..].find('"').map(|j| i + j + 1))
        .and_then(|i| line[i..].find('"').map(|j| (i, i + j)))
        .map(|(i, j)| &line[i..j])
}

fn collect_lang_features(path: &Path) -> Vec<Feature> {
    let mut contents = String::new();
    t!(t!(File::open(path)).read_to_string(&mut contents));

    contents.lines()
        .filter_map(|line| {
            let mut parts = line.trim().split(",");
            let level = match parts.next().map(|l| l.trim().trim_left_matches('(')) {
                Some("active") => Status::Unstable,
                Some("removed") => Status::Unstable,
                Some("accepted") => Status::Stable,
                _ => return None,
            };
            let name = parts.next().unwrap().trim();
            let since = parts.next().unwrap().trim().trim_matches('"');
            Some(Feature {
                name: name.to_owned(),
                level: level,
                since: since.to_owned(),
            })
        })
        .collect()
}
<|endoftext|>


<commit_before>#![feature(globs)]

extern crate piston;

extern crate hgl;
extern crate gl;
extern crate sdl2_game_window;

use sdl2_game_window::GameWindowSDL2;
use piston::{
    Game,
    GameIteratorSettings,
    GameWindowSettings,
    RenderArgs
};

use std::mem::size_of;
use hgl::{Shader, Program, Triangles, Vbo, Vao};

#[allow(dead_code)]
pub struct App {
    program: Program,
    vao: Vao,
    vbo: Vbo
}

static VERTEX_SHADER: &'static str = r"
    attribute vec2 position;

    void main() {
        gl_Position = vec4(position, 0.0, 1.0);
    }
";

static FRAGMENT_SHADER: &'static str = r"
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
";

impl App {
    /// Creates a new application.
    pub fn new() -> App {
        let vao = Vao::new();
        vao.bind();

        let program = Program::link([Shader::compile(VERTEX_SHADER, hgl::VertexShader),
        Shader::compile(FRAGMENT_SHADER, hgl::FragmentShader)]).unwrap();
        program.bind();

        let vbo = Vbo::from_data([
            0.0f32, 0.5, 1.0, 0.0, 0.0,
            0.5,   -0.5, 0.0, 1.0, 0.0,
            -0.5,  -0.5, 0.0, 0.0, 1.0
        ], hgl::StaticDraw);

        vao.enable_attrib(&program, "position", gl::FLOAT, 2, 5*size_of::<f32>() as i32, 0);
        vao.enable_attrib(&program, "color", gl::FLOAT, 3, 5*size_of::<f32>() as i32, 2*size_of::<f32>());
        vbo.bind();

        App {
            program: program,
            vao: vao,
            vbo: vbo
        }
    }
}

impl Game for App {
    fn render(&mut self, args: &mut RenderArgs) {
        gl::Viewport(0, 0, args.width as i32, args.height as i32);
        gl::ClearColor(0.0, 0.0, 0.0, 0.1);
        gl::Clear(gl::COLOR_BUFFER_BIT);
        self.vao.draw_array(Triangles, 0, 3);
    }
}

fn main() {
    let mut window = GameWindowSDL2::new(
        GameWindowSettings {
            title: "Test".to_string(),
            size: [800, 600],
            fullscreen: false,
            exit_on_esc: true
        }
    );

    let game_iter_settings = GameIteratorSettings {
            updates_per_second: 120,
            max_frames_per_second: 60,
        };
    App::new().run(&mut window, &game_iter_settings);
}

<commit_msg>Removed hgl-rs triangle example<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use font::{Font, FontDescriptor, FontGroup, FontHandleMethods, SelectorPlatformIdentifier};
use font::{SpecifiedFontStyle, UsedFontStyle};
use font_list::FontList;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;

use azure::azure_hl::BackendType;
use collections::hashmap::HashMap;
use servo_util::cache::{Cache, LRUCache};
use servo_util::time::ProfilerChan;

use std::rc::Rc;
use std::cell::RefCell;

/// Information needed to create a font context.
#[deriving(Clone)]
pub struct FontContextInfo {
    /// The painting backend we're using.
    pub backend: BackendType,

    /// Whether we need a font list.
    pub needs_font_list: bool,

    /// A channel up to the profiler.
    pub profiler_chan: ProfilerChan,
}

pub trait FontContextHandleMethods {
    fn create_font_from_identifier(&self, ~str, UsedFontStyle) -> Result<FontHandle, ()>;
}

pub struct FontContext {
    pub instance_cache: LRUCache<FontDescriptor, Rc<RefCell<Font>>>,
    pub font_list: Option<FontList>, // only needed by layout
    pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>,
    pub handle: FontContextHandle,
    pub backend: BackendType,
    pub generic_fonts: HashMap<~str,~str>,
    pub profiler_chan: ProfilerChan,
}

impl FontContext {
    pub fn new(info: FontContextInfo) -> FontContext {
        let handle = FontContextHandle::new();
        let font_list = if info.needs_font_list {
            Some(FontList::new(&handle, info.profiler_chan.clone()))
        } else {
            None
        };

        // TODO: Allow users to specify these.
        let mut generic_fonts = HashMap::with_capacity(5);
        generic_fonts.insert("serif".to_owned(), "Times New Roman".to_owned());
        generic_fonts.insert("sans-serif".to_owned(), "Arial".to_owned());
        generic_fonts.insert("cursive".to_owned(), "Apple Chancery".to_owned());
        generic_fonts.insert("fantasy".to_owned(), "Papyrus".to_owned());
        generic_fonts.insert("monospace".to_owned(), "Menlo".to_owned());

        FontContext {
            instance_cache: LRUCache::new(10),
            font_list: font_list,
            group_cache: LRUCache::new(10),
            handle: handle,
            backend: info.backend,
            generic_fonts: generic_fonts,
            profiler_chan: info.profiler_chan.clone(),
        }
    }

    pub fn get_resolved_font_for_style(&mut self, style: &SpecifiedFontStyle)
                                       -> Rc<RefCell<FontGroup>> {
        match self.group_cache.find(style) {
            Some(fg) => {
                debug!("font group cache hit");
                fg
            },
            None => {
                debug!("font group cache miss");
                let fg = self.create_font_group(style);
                self.group_cache.insert(style.clone(), fg.clone());
                fg
            }
        }
    }

    pub fn get_font_by_descriptor(&mut self, desc: &FontDescriptor)
                                  -> Result<Rc<RefCell<Font>>, ()> {
        match self.instance_cache.find(desc) {
            Some(f) => {
                debug!("font cache hit");
                Ok(f)
            },
            None => {
                debug!("font cache miss");
                let result = self.create_font_instance(desc);
                match result.clone() {
                    Ok(ref font) => {
                        self.instance_cache.insert(desc.clone(), font.clone());
                    }, _ => {}
                };
                result
            }
        }
    }

    fn transform_family(&self, family: &~str) -> ~str {
        debug!("(transform family) searching for `{:s}`", family.as_slice());
        match self.generic_fonts.find(family) {
            None => family.to_owned(),
            Some(mapped_family) => (*mapped_family).clone()
        }
    }

    fn create_font_group(&mut self, style: &SpecifiedFontStyle) -> Rc<RefCell<FontGroup>> {
        let mut fonts = vec!();

        debug!("(create font group) --- starting ---");

        // TODO(Issue #193): make iteration over 'font-family' more robust.
        for family in style.families.iter() {
            let transformed_family_name = self.transform_family(family);
            debug!("(create font group) transformed family is `{:s}`", transformed_family_name);
            let mut found = false;

            let result = match self.font_list {
                Some(ref mut fl) => {
                    let font_in_family = fl.find_font_in_family(&transformed_family_name, style);
                    match font_in_family {
                        Some(font_entry) => {
                            let font_id =
                                SelectorPlatformIdentifier(font_entry.handle.face_identifier());
                            let font_desc = FontDescriptor::new((*style).clone(), font_id);
                            Some(font_desc)
                        },
                        None => {
                            None
                        }
                    }
                }
                None => None,
            };

            match result {
                Some(ref result) => {
                    found = true;
                    let instance = self.get_font_by_descriptor(result);
                    let _ = instance.map(|font| fonts.push(font.clone()));
                },
                _ => {}
            }

            if !found {
                debug!("(create font group) didn't find `{:s}`", transformed_family_name);
            }
        }

        if fonts.len() == 0 {
            let last_resort = FontList::get_last_resort_font_families();
            for family in last_resort.iter() {
                let font_desc = match self.font_list {
                    Some(ref mut font_list) => {
                        let font_desc = {
                            let font_entry = font_list.find_font_in_family(family, style);
                            match font_entry {
                                Some(v) => {
                                    let font_id =
                                        SelectorPlatformIdentifier(v.handle.face_identifier());
                                    Some(FontDescriptor::new((*style).clone(), font_id))
                                },
                                None => {
                                    None
                                }
                            }
                        };
                        font_desc
                    },
                    None => {
                        None
                    }
                };

                match font_desc {
                    Some(ref fd) => {
                        let instance = self.get_font_by_descriptor(fd);
                        let _ = instance.map(|font| fonts.push(font.clone()));
                    },
                    None => { }
                };
            }
        }
        assert!(fonts.len() > 0);
        // TODO(Issue #179): Split FontStyle into specified and used styles
        let used_style = (*style).clone();

        debug!("(create font group) --- finished ---");

        Rc::new(
            RefCell::new(
                FontGroup::new(style.families.clone(), &used_style, fonts)))
    }

    fn create_font_instance(&self, desc: &FontDescriptor) -> Result<Rc<RefCell<Font>>, ()> {
        return match &desc.selector {
            // TODO(Issue #174): implement by-platform-name font selectors.
            &SelectorPlatformIdentifier(ref identifier) => {
                let result_handle = self.handle.create_font_from_identifier((*identifier).clone(),
                                                                            desc.style.clone());
                result_handle.and_then(|handle| {
                    Ok(
                        Rc::new(
                            RefCell::new(
                                Font::new_from_adopted_handle(self,
                                                              handle,
                                                              &desc.style,
                                                              self.backend))))
                })
            }
        };
    }
}
<commit_msg>auto merge of #2426 : bjwbell/servo/add-message-to-assert, r=pcwalton<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use font::{Font, FontDescriptor, FontGroup, FontHandleMethods, SelectorPlatformIdentifier};
use font::{SpecifiedFontStyle, UsedFontStyle};
use font_list::FontList;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;

use azure::azure_hl::BackendType;
use collections::hashmap::HashMap;
use servo_util::cache::{Cache, LRUCache};
use servo_util::time::ProfilerChan;

use std::rc::Rc;
use std::cell::RefCell;

/// Information needed to create a font context.
#[deriving(Clone)]
pub struct FontContextInfo {
    /// The painting backend we're using.
    pub backend: BackendType,

    /// Whether we need a font list.
    pub needs_font_list: bool,

    /// A channel up to the profiler.
    pub profiler_chan: ProfilerChan,
}

pub trait FontContextHandleMethods {
    fn create_font_from_identifier(&self, ~str, UsedFontStyle) -> Result<FontHandle, ()>;
}

pub struct FontContext {
    pub instance_cache: LRUCache<FontDescriptor, Rc<RefCell<Font>>>,
    pub font_list: Option<FontList>, // only needed by layout
    pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>,
    pub handle: FontContextHandle,
    pub backend: BackendType,
    pub generic_fonts: HashMap<~str,~str>,
    pub profiler_chan: ProfilerChan,
}

impl FontContext {
    pub fn new(info: FontContextInfo) -> FontContext {
        let handle = FontContextHandle::new();
        let font_list = if info.needs_font_list {
            Some(FontList::new(&handle, info.profiler_chan.clone()))
        } else {
            None
        };

        // TODO: Allow users to specify these.
        let mut generic_fonts = HashMap::with_capacity(5);
        generic_fonts.insert("serif".to_owned(), "Times New Roman".to_owned());
        generic_fonts.insert("sans-serif".to_owned(), "Arial".to_owned());
        generic_fonts.insert("cursive".to_owned(), "Apple Chancery".to_owned());
        generic_fonts.insert("fantasy".to_owned(), "Papyrus".to_owned());
        generic_fonts.insert("monospace".to_owned(), "Menlo".to_owned());

        FontContext {
            instance_cache: LRUCache::new(10),
            font_list: font_list,
            group_cache: LRUCache::new(10),
            handle: handle,
            backend: info.backend,
            generic_fonts: generic_fonts,
            profiler_chan: info.profiler_chan.clone(),
        }
    }

    pub fn get_resolved_font_for_style(&mut self, style: &SpecifiedFontStyle)
                                       -> Rc<RefCell<FontGroup>> {
        match self.group_cache.find(style) {
            Some(fg) => {
                debug!("font group cache hit");
                fg
            },
            None => {
                debug!("font group cache miss");
                let fg = self.create_font_group(style);
                self.group_cache.insert(style.clone(), fg.clone());
                fg
            }
        }
    }

    pub fn get_font_by_descriptor(&mut self, desc: &FontDescriptor)
                                  -> Result<Rc<RefCell<Font>>, ()> {
        match self.instance_cache.find(desc) {
            Some(f) => {
                debug!("font cache hit");
                Ok(f)
            },
            None => {
                debug!("font cache miss");
                let result = self.create_font_instance(desc);
                match result.clone() {
                    Ok(ref font) => {
                        self.instance_cache.insert(desc.clone(), font.clone());
                    }, _ => {}
                };
                result
            }
        }
    }

    fn transform_family(&self, family: &~str) -> ~str {
        debug!("(transform family) searching for `{:s}`", family.as_slice());
        match self.generic_fonts.find(family) {
            None => family.to_owned(),
            Some(mapped_family) => (*mapped_family).clone()
        }
    }

    fn create_font_group(&mut self, style: &SpecifiedFontStyle) -> Rc<RefCell<FontGroup>> {
        let mut fonts = vec!();

        debug!("(create font group) --- starting ---");

        // TODO(Issue #193): make iteration over 'font-family' more robust.
        for family in style.families.iter() {
            let transformed_family_name = self.transform_family(family);
            debug!("(create font group) transformed family is `{:s}`", transformed_family_name);
            let mut found = false;

            let result = match self.font_list {
                Some(ref mut fl) => {
                    let font_in_family = fl.find_font_in_family(&transformed_family_name, style);
                    match font_in_family {
                        Some(font_entry) => {
                            let font_id =
                                SelectorPlatformIdentifier(font_entry.handle.face_identifier());
                            let font_desc = FontDescriptor::new((*style).clone(), font_id);
                            Some(font_desc)
                        },
                        None => {
                            None
                        }
                    }
                }
                None => None,
            };

            match result {
                Some(ref result) => {
                    found = true;
                    let instance = self.get_font_by_descriptor(result);
                    let _ = instance.map(|font| fonts.push(font.clone()));
                },
                _ => {}
            }

            if !found {
                debug!("(create font group) didn't find `{:s}`", transformed_family_name);
            }
        }

        if fonts.len() == 0 {
            let last_resort = FontList::get_last_resort_font_families();
            for family in last_resort.iter() {
                let font_desc = match self.font_list {
                    Some(ref mut font_list) => {
                        let font_desc = {
                            let font_entry = font_list.find_font_in_family(family, style);
                            match font_entry {
                                Some(v) => {
                                    let font_id =
                                        SelectorPlatformIdentifier(v.handle.face_identifier());
                                    Some(FontDescriptor::new((*style).clone(), font_id))
                                },
                                None => {
                                    None
                                }
                            }
                        };
                        font_desc
                    },
                    None => {
                        None
                    }
                };

                match font_desc {
                    Some(ref fd) => {
                        let instance = self.get_font_by_descriptor(fd);
                        let _ = instance.map(|font| fonts.push(font.clone()));
                    },
                    None => { }
                };
            }
        }
        assert!(fonts.len() > 0, "No matching font(s), are the appropriate fonts installed?");
        // TODO(Issue #179): Split FontStyle into specified and used styles
        let used_style = (*style).clone();

        debug!("(create font group) --- finished ---");

        Rc::new(
            RefCell::new(
                FontGroup::new(style.families.clone(), &used_style, fonts)))
    }

    fn create_font_instance(&self, desc: &FontDescriptor) -> Result<Rc<RefCell<Font>>, ()> {
        return match &desc.selector {
            // TODO(Issue #174): implement by-platform-name font selectors.
            &SelectorPlatformIdentifier(ref identifier) => {
                let result_handle = self.handle.create_font_from_identifier((*identifier).clone(),
                                                                            desc.style.clone());
                result_handle.and_then(|handle| {
                    Ok(
                        Rc::new(
                            RefCell::new(
                                Font::new_from_adopted_handle(self,
                                                              handle,
                                                              &desc.style,
                                                              self.backend))))
                })
            }
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>Cosmetic changes.<commit_after><|endoftext|>


<commit_before><commit_msg>Hotfix: Ignore code snippet here<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary call<commit_after><|endoftext|>


<commit_before><commit_msg>Reimplement the hasher<commit_after><|endoftext|>


<commit_before><commit_msg>Implement $replace() and $replacen()<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test<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.

// Test that `Clone` is correctly implemented for builtin types.
// Also test that cloning an array or a tuple is done right, i.e.
// each component is cloned.

fn test_clone<T: Clone>(arg: T) {
    let _ = arg.clone();
}

fn foo() { }

#[derive(Debug, PartialEq, Eq)]
struct S(i32);

impl Clone for S {
    fn clone(&self) -> Self {
        S(self.0 + 1)
    }
}

fn main() {
    test_clone(foo);
    test_clone([1; 56]);
    test_clone((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1));

    let a = [S(0), S(1), S(2)];
    let b = [S(1), S(2), S(3)];
    assert_eq!(b, a.clone());

    let a = (
        (S(1), S(0)),
        (
            (S(0), S(0), S(1)),
            S(0)
        )
    );
    let b = (
        (S(2), S(1)),
        (
            (S(1), S(1), S(2)),
            S(1)
        )
    );
    assert_eq!(b, a.clone());
}
<|endoftext|>


<commit_before><commit_msg>Add handler for settled events to serial_16550<commit_after><|endoftext|>


<commit_before><commit_msg>start itermut draft<commit_after>#![allow(dead_code)]

/// # Mutable Iterators
///
/// We will implement a simple tree that could, say, represent a simple DOM
/// structure.  You may notice that we don't actually allow for text in our
/// simple representation, but this isn't important here, what we really want
/// to investigate is how we would implement a mutable iterator using our custom
/// data structure.  Our DOM structure will only allow for four different types
/// of nodes: Header, Paragraph, Text, and Images.

enum NodeType {
    Header,
    Paragraph,
    Text,
    Image,
}

/// Each node with have a list of `children` nodes and a tag for the respective
/// DOM element type.

struct DomNode {
    children: Vec<DomNode>,
    node_type: NodeType
}

/// To implement an iterator, we essentially just need to tell Rust two things:
///   a. What kind of elements will we be iteratorating over?  In this example
///      we will be iteratorating over the nodes of our Dom, so we will want
///      to iterate over `NodeType`s.
///   b. What is the next element?
///
/// We will therefore have the responsibility of keeping track of where we are at
/// while iteratorating over our DOM.  We will do this by constructing what is
/// oftern called an "iterator interface".  We make one like this:

struct DomMutIterator<'a> {
    data: &'a mut DomNode,
    cursor: usize,
}

/// We provide answers for the questions posted above for Rust by implementing an
/// `Iterator` for our iterator interface.

impl<'a> Iterator for DomMutIterator<'a> {
    type Item = &'a mut NodeType;
    fn next(&mut self) -> Option<&'a mut NodeType> {

        // This part will require some thought...

        unimplemented!();
    }
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Updates<commit_after><|endoftext|>


<commit_before><commit_msg>practice<commit_after>fn main() {
    let x: i32 = 8;
    {
        println!("{}", x);
        let x = 12;
        println!("{}", x);
    }
    println!("{}", x);
    let x = 42;
    println!("{}", x);
}
<|endoftext|>