<commit_before>extern crate robots;

use robots::actors::{Actor,ActorCell};
use std::sync::Mutex;
use std::any::Any;
use std::thread;
use std::time;
use super::super::gpioaccess::{DirectionProxied,PinProxyContract,PwmProxyContract};
use super::super::gpioaccess::proxyimpl::{PinProxy,PwmProxy};

#[derive(Copy, Clone, PartialEq,Debug)]
pub enum PinCommands {
	Blink(u64),
	Switch,
}

pub struct PinActor {
	pinproxy :  Mutex<PinProxy>,
}

impl Actor for PinActor {
	fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<PinCommands>(_message){
			match *_message {
				PinCommands::Blink(times) => {
					let pin = self.pinproxy.lock().unwrap();
					match pin.export() {
						Ok(()) => {
							println!("Pin exported");
							for _ in 1..times {
								pin.set_direction(DirectionProxied::Out);
								pin.set_direction(DirectionProxied::High);
								thread::sleep(time::Duration::from_millis(400));
								pin.set_direction(DirectionProxied::Low);
								thread::sleep(time::Duration::from_millis(400));
								println!("Blink");
							}
							match pin.unexport() {
								Ok(()) => {
									println!("Pin unexported");
								}
								_ => {}
							}
						}
						_ => {}
					}
				},
				PinCommands::Switch => { }
			}
		}
	}
}

impl PinActor{
	pub fn new(pin_number: u64) -> PinActor {
		PinActor{ pinproxy : Mutex::new(PinProxy::new(pin_number)) }
	}
}

#[derive(Copy, Clone, PartialEq,Debug)]
pub enum PwmCommands {
	MoveToDegree(u16)
}

pub struct PwmActor {
	pwmproxy :  Result<Mutex<PwmProxy>,()>,
}

impl Actor for PwmActor {
	fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		println!("pwm received message");
		if let Ok(_message) = Box::<Any>::downcast::<PwmCommands>(_message){
			println!("pwm recognized command");
			match *_message {
				PwmCommands::MoveToDegree(degree) => {
					println!("pwm movetodegree");
					match self.pwmproxy {
						Ok(ref pwmproxyresult) =>
						{
							let pwm = pwmproxyresult.lock().unwrap();
							match pwm.export() {
								Ok(()) => {
									println!("Pwm exported");
									match pwm.set_period_ns(1_500_000)
									{
										Ok(()) => {
											println!("Pwm setting period");
											match pwm.enable(true)
											{
												Ok(()) => {
													println!("Pwm enable");
													for x in 1..10 {
														println!("Pwm {}",x);
														pwm.increase_to_max(0.05);
														pwm.decrease_to_minimum(0.05);
													}
													match pwm.enable(false)
													{
														Ok(()) => {
															println!("Pwm disable");
														}
														_ => println!("Pwm disabled failed")
													}
												}
												_ => println!("Pwm enabled failed")
											}
										}
										_ => println!("Pwm set period failed")
									}
									match pwm.unexport() {
										Ok(()) => {
											println!("Pwm unexported");
										}
										_ => println!("Pwm unexport failed")
									}
								}
								_ => println!("Pwm export failed")
							}
						}
						_ => println!("No Pwm")
					}

					println!("pwm done");
				}
			}
		}
	}
}

impl PwmActor{
	pub fn new(number: u32) -> PwmActor {
		match PwmProxy::new(0,number)
		{
			Ok(pwmproxy) =>  PwmActor{ pwmproxy : Ok(Mutex::new(pwmproxy)) },
			_ => PwmActor{ pwmproxy : Err(()) },
		}
	}
}<commit_msg>modif<commit_after>extern crate robots;

use robots::actors::{Actor,ActorCell};
use std::sync::Mutex;
use std::any::Any;
use std::thread;
use std::time;
use super::super::gpioaccess::{DirectionProxied,PinProxyContract,PwmProxyContract};
use super::super::gpioaccess::proxyimpl::{PinProxy,PwmProxy};

#[derive(Copy, Clone, PartialEq,Debug)]
pub enum PinCommands {
	Blink(u64),
	Switch,
}

pub struct PinActor {
	pinproxy :  Mutex<PinProxy>,
}

impl Actor for PinActor {
	fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<PinCommands>(_message){
			match *_message {
				PinCommands::Blink(times) => {
					let pin = self.pinproxy.lock().unwrap();
					match pin.export() {
						Ok(()) => {
							println!("Pin exported");
							for _ in 1..times {
								pin.set_direction(DirectionProxied::Out);
								pin.set_direction(DirectionProxied::High);
								thread::sleep(time::Duration::from_millis(400));
								pin.set_direction(DirectionProxied::Low);
								thread::sleep(time::Duration::from_millis(400));
								println!("Blink");
							}
							match pin.unexport() {
								Ok(()) => {
									println!("Pin unexported");
								}
								_ => {}
							}
						}
						_ => {}
					}
				},
				PinCommands::Switch => { }
			}
		}
	}
}

impl PinActor{
	pub fn new(pin_number: u64) -> PinActor {
		PinActor{ pinproxy : Mutex::new(PinProxy::new(pin_number)) }
	}
}

#[derive(Copy, Clone, PartialEq,Debug)]
pub enum PwmCommands {
	MoveToDegree(u16)
}

pub struct PwmActor {
	pwmproxy :  Result<Mutex<PwmProxy>,()>,
}

impl Actor for PwmActor {
	fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		println!("pwm received message");
		if let Ok(_message) = Box::<Any>::downcast::<PwmCommands>(_message){
			println!("pwm recognized command");
			match *_message {
				PwmCommands::MoveToDegree(degree) => {
					println!("pwm movetodegree");
					match self.pwmproxy {
						Ok(ref pwmproxyresult) =>
						{
							let pwm = pwmproxyresult.lock().unwrap();
							match pwm.export() {
								Ok(()) => {
									println!("Pwm exported");
									match pwm.set_period_ns(20_000)
									{
										Ok(()) => {
											println!("Pwm setting period");
											match pwm.enable(true)
											{
												Ok(()) => {
													println!("Pwm enable");
													for x in 1..10 {
														println!("Pwm {}",x);
														pwm.increase_to_max(0.05);
														pwm.decrease_to_minimum(0.05);
													}
													match pwm.enable(false)
													{
														Ok(()) => {
															println!("Pwm disable");
														}
														_ => println!("Pwm disabled failed")
													}
												}
												_ => println!("Pwm enabled failed")
											}
										}
										_ => println!("Pwm set period failed")
									}
									match pwm.unexport() {
										Ok(()) => {
											println!("Pwm unexported");
										}
										_ => println!("Pwm unexport failed")
									}
								}
								_ => println!("Pwm export failed")
							}
						}
						_ => println!("No Pwm")
					}

					println!("pwm done");
				}
			}
		}
	}
}

impl PwmActor{
	pub fn new(number: u32) -> PwmActor {
		match PwmProxy::new(0,number)
		{
			Ok(pwmproxy) =>  PwmActor{ pwmproxy : Ok(Mutex::new(pwmproxy)) },
			_ => PwmActor{ pwmproxy : Err(()) },
		}
	}
}<|endoftext|>


<commit_before>use std;
use base::*;
use super::{LoudsTrie, NodeID, LoudsPos, LinkID};

struct History<'a> {
    trie_: &'a LoudsTrie,
    node_id_: NodeID,
    louds_pos_: LoudsPos,
    link_id_: LinkID,
    key_pos_: u32,
    //key_id_: u32,
}

impl<'a> History<'a> {
    fn new(trie: &'a LoudsTrie, node_id: NodeID, louds_pos: LoudsPos,
           link_id: LinkID, key_pos: u32) -> History<'a> {
        History { trie_: trie, node_id_: node_id, louds_pos_: louds_pos,
                  link_id_: link_id, key_pos_: key_pos }
    }
}

struct State<'a> {
    history_: Vec<History<'a> >,
    key_buf_: Vec<u8>,
}

impl<'a> State<'a> {
    fn new() -> State<'a> {
        State { history_: Vec::new(), key_buf_: Vec::new() }
    }

    fn push<'b>(&mut self, key: &'b[u8], trie: &'a LoudsTrie, node_id: NodeID,
                louds_pos: LoudsPos, link_id: LinkID, key_pos: u32) {
        self.key_buf_.extend(key);
        self.history_.push(History::new(trie, node_id, louds_pos, link_id,
                                        key_pos));
    }

    fn get_key(&self) -> &[u8] {
        &self.key_buf_[..]
    }

    fn pop(&mut self) -> Option<History<'a> > {
        self.history_.pop()
    }

    fn get_node_id(&self) -> NodeID {
        self.history_.last().unwrap().node_id_
    }
}

pub struct Nav<'a> {
    state_: State<'a>,
    trie_: &'a LoudsTrie,
}

impl<'a> Nav<'a> {
    pub fn new(trie: &'a LoudsTrie) -> Nav<'a> {
        Nav { state_: State::new(), trie_: trie }
    }

    //pub fn has_child(&self) -> bool {
    //fn child_pos(&self) -> Option<(NodeID, LoudsPos)> {
    pub fn go_to_child(&mut self) -> bool {
        // For lookups, marisa does caching based on the input character.
        // We can't do that here. May want to remove or rethink the cache
        // implementation in light of this.

        //let louds = &self.trie_.louds_;
        //let state = &mut self.state_;
        //let link_flags = &self.trie_.link_flags_;

        if let Some((node_id, louds_pos))
        = self.trie_.child_pos(self.state_.get_node_id()) {

            /*
            let mut link_id = INVALID_LINK_ID;
            do {
                if link_flags[state.node_id()] {
                    //link_id = update_link_id(link_id, state.node_id());

                    //const std::size_t prev_query_pos = state.query_pos();
                    //if (match(agent, get_link(state.node_id(), link_id))) {
                    //  return true;
                    //} else if (state.query_pos() != prev_query_pos) {
                    //  return false;
                    //}
                } else {
                    // Character for node
                    bases_[state.node_id()]

                    state.set_query_pos(state.query_pos() + 1);
                    return true;
                }
                state.set_node_id(state.node_id() + 1);
                ++louds_pos;
            } while (louds_[louds_pos]);
            */
            false

        } else {
            false
        }
    }
    pub fn has_sibling(&self) -> bool {
        panic!("not implemented")
    }
    pub fn go_to_sibling(&mut self) -> bool {
        panic!("not implemented")
    }
    pub fn has_parent(&self) -> bool {
        panic!("not implemented")
    }
    pub fn go_to_parent(&self) -> bool {
        panic!("not implemented")
    }
    pub fn is_terminal(&self) -> bool {
        panic!("not implemented")
    }
    pub fn get_string(&self) -> &str {
        panic!("not implemented")
    }
    pub fn is_end(&self) -> bool {
        panic!("not implemented")
    }

}

/*

bool LoudsTrie::lookup(Agent &agent) const {
  MARISA_DEBUG_IF(!agent.has_state(), MARISA_STATE_ERROR);

  State &state = agent.state();
  state.lookup_init();
  while (state.query_pos() < agent.query().length()) {
    if (!find_child(agent)) {
      return false;
    }
  }
  if (!terminal_flags_[state.node_id()]) {
    return false;
  }
  agent.set_key(agent.query().ptr(), agent.query().length());
  agent.set_key(terminal_flags_.rank1(state.node_id()));
  return true;
}

bool LoudsTrie::find_child(Agent &agent) const {
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);

  State &state = agent.state();
  const std::size_t cache_id = get_cache_id(state.node_id(),
      agent.query()[state.query_pos()]);
  if (state.node_id() == cache_[cache_id].parent()) {
    if (cache_[cache_id].extra() != MARISA_INVALID_EXTRA) {
      if (!match(agent, cache_[cache_id].link())) {
        return false;
      }
    } else {
      state.set_query_pos(state.query_pos() + 1);
    }
    state.set_node_id(cache_[cache_id].child());
    return true;
  }

  std::size_t louds_pos = louds_.select0(state.node_id()) + 1;
  if (!louds_[louds_pos]) {
    return false;
  }
  state.set_node_id(louds_pos - state.node_id() - 1);
  std::size_t link_id = MARISA_INVALID_LINK_ID;
  do {
    if (link_flags_[state.node_id()]) {
      link_id = update_link_id(link_id, state.node_id());
      const std::size_t prev_query_pos = state.query_pos();
      if (match(agent, get_link(state.node_id(), link_id))) {
        return true;
      } else if (state.query_pos() != prev_query_pos) {
        return false;
      }
    } else if (bases_[state.node_id()] ==
        (UInt8)agent.query()[state.query_pos()]) {
      state.set_query_pos(state.query_pos() + 1);
      return true;
    }
    state.set_node_id(state.node_id() + 1);
    ++louds_pos;
  } while (louds_[louds_pos]);
  return false;
}

std::size_t LoudsTrie::get_cache_id(std::size_t node_id, char label) const {
  return (node_id ^ (node_id << 5) ^ (UInt8)label) & cache_mask_;
}

std::size_t LoudsTrie::get_cache_id(std::size_t node_id) const {
  return node_id & cache_mask_;
}

bool LoudsTrie::match(Agent &agent, std::size_t link) const {
  if (next_trie_.get() != NULL) {
    return next_trie_->match_(agent, link);
  } else {
    return tail_.match(agent, link);
  }
}

bool LoudsTrie::match_(Agent &agent, std::size_t node_id) const {
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);
  MARISA_DEBUG_IF(node_id == 0, MARISA_RANGE_ERROR);

  State &state = agent.state();
  for ( ; ; ) {
    const std::size_t cache_id = get_cache_id(node_id);
    if (node_id == cache_[cache_id].child()) {
      if (cache_[cache_id].extra() != MARISA_INVALID_EXTRA) {
        if (!match(agent, cache_[cache_id].link())) {
          return false;
        }
      } else if (cache_[cache_id].label() ==
          agent.query()[state.query_pos()]) {
        state.set_query_pos(state.query_pos() + 1);
      } else {
        return false;
      }

      node_id = cache_[cache_id].parent();
      if (node_id == 0) {
        return true;
      } else if (state.query_pos() >= agent.query().length()) {
        return false;
      }
      continue;
    }

    if (link_flags_[node_id]) {
      if (next_trie_.get() != NULL) {
        if (!match(agent, get_link(node_id))) {
          return false;
        }
      } else if (!tail_.match(agent, get_link(node_id))) {
        return false;
      }
    } else if (bases_[node_id] == (UInt8)agent.query()[state.query_pos()]) {
      state.set_query_pos(state.query_pos() + 1);
    } else {
      return false;
    }

    if (node_id <= num_l1_nodes_) {
      return true;
    } else if (state.query_pos() >= agent.query().length()) {
      return false;
    }
    node_id = louds_.select1(node_id) - node_id - 1;
  }
}

bool Tail::match(Agent &agent, std::size_t offset) const {
  MARISA_DEBUG_IF(buf_.empty(), MARISA_STATE_ERROR);
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);

  State &state = agent.state();
  if (end_flags_.empty()) {
    const char * const ptr = &buf_[offset] - state.query_pos();
    do {
      if (ptr[state.query_pos()] != agent.query()[state.query_pos()]) {
        return false;
      }
      state.set_query_pos(state.query_pos() + 1);
      if (ptr[state.query_pos()] == '\0') {
        return true;
      }
    } while (state.query_pos() < agent.query().length());
    return false;
  } else {
    do {
      if (buf_[offset] != agent.query()[state.query_pos()]) {
        return false;
      }
      state.set_query_pos(state.query_pos() + 1);
      if (end_flags_[offset++]) {
        return true;
      }
    } while (state.query_pos() < agent.query().length());
    return false;
  }
}

*/
<commit_msg>nav.rs work<commit_after>use std;
use base::*;
use super::{LoudsTrie, NodeID, LoudsPos, LinkID};

struct History<'a> {
    trie_: &'a LoudsTrie,
    node_id_: NodeID,
    louds_pos_: LoudsPos,
    link_id_: LinkID,
    key_pos_: u32,
    //key_id_: u32,
}

impl<'a> History<'a> {
    fn new(trie: &'a LoudsTrie, node_id: NodeID, louds_pos: LoudsPos,
           link_id: LinkID, key_pos: u32) -> History<'a> {
        History { trie_: trie, node_id_: node_id, louds_pos_: louds_pos,
                  link_id_: link_id, key_pos_: key_pos }
    }
}

struct State<'a> {
    history_: Vec<History<'a> >,
    key_buf_: Vec<u8>,
}

impl<'a> State<'a> {
    fn new() -> State<'a> {
        State { history_: Vec::new(), key_buf_: Vec::new() }
    }

    fn push<'b>(&mut self, key: &'b[u8], trie: &'a LoudsTrie, node_id: NodeID,
                louds_pos: LoudsPos, link_id: LinkID) {
        self.key_buf_.extend(key);
        assert!(self.key_buf_.len() <= std::u32::MAX as usize);
        self.history_.push(History::new(trie, node_id, louds_pos, link_id,
                                        self.key_buf_.len() as u32));
    }

    fn get_key(&self) -> &[u8] {
        &self.key_buf_[..]
    }

    fn pop(&mut self) -> Option<History<'a> > {
        self.history_.pop()
    }

    fn get_node_id(&self) -> NodeID {
        self.history_.last().unwrap().node_id_
    }
}

pub struct Nav<'a> {
    state_: State<'a>,
    trie_: &'a LoudsTrie,
}

// For lookups, marisa does caching based on the input character.
// We can't do that here. May want to remove or rethink the cache
// implementation in light of this.

impl<'a> Nav<'a> {
    pub fn new(trie: &'a LoudsTrie) -> Nav<'a> {
        Nav { state_: State::new(), trie_: trie }
    }

    pub fn has_child(&mut self) -> bool {
        self.trie_.has_child(self.state_.get_node_id())
    }
    pub fn go_to_child(&mut self) -> bool {
        let init_node_id = self.state_.get_node_id();
        if let Some((node_id, louds_pos)) = self.trie_.child_pos(init_node_id) {
            if self.trie_.link_flags_.at(node_id.0 as usize) {
                //link_id = update_link_id(link_id, state.node_id());

                //const std::size_t prev_query_pos = state.query_pos();
                //if (match(agent, get_link(state.node_id(), link_id))) {
                //  return true;
                //} else if (state.query_pos() != prev_query_pos) {
                //  return false;
                //}
            } else {
                // Character for node
                let node_char = [ self.trie_.bases_[node_id.0 as usize] ];

                // Not sure what this should be
                let link_id = LinkID(0);

                self.state_.push(&node_char, self.trie_, node_id, louds_pos,
                                 link_id);
                return true;
            }
            false
        } else {
            false
        }
    }
    pub fn has_sibling(&self) -> bool {
        panic!("not implemented")
    }
    pub fn go_to_sibling(&mut self) -> bool {
        panic!("not implemented")
    }
    pub fn has_parent(&self) -> bool {
        panic!("not implemented")
    }
    pub fn go_to_parent(&self) -> bool {
        panic!("not implemented")
    }
    pub fn is_terminal(&self) -> bool {
        panic!("not implemented")
    }
    pub fn get_string(&self) -> &str {
        panic!("not implemented")
    }
    pub fn is_end(&self) -> bool {
        panic!("not implemented")
    }

}

/*

bool LoudsTrie::lookup(Agent &agent) const {
  MARISA_DEBUG_IF(!agent.has_state(), MARISA_STATE_ERROR);

  State &state = agent.state();
  state.lookup_init();
  while (state.query_pos() < agent.query().length()) {
    if (!find_child(agent)) {
      return false;
    }
  }
  if (!terminal_flags_[state.node_id()]) {
    return false;
  }
  agent.set_key(agent.query().ptr(), agent.query().length());
  agent.set_key(terminal_flags_.rank1(state.node_id()));
  return true;
}

bool LoudsTrie::find_child(Agent &agent) const {
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);

  State &state = agent.state();
  const std::size_t cache_id = get_cache_id(state.node_id(),
      agent.query()[state.query_pos()]);
  if (state.node_id() == cache_[cache_id].parent()) {
    if (cache_[cache_id].extra() != MARISA_INVALID_EXTRA) {
      if (!match(agent, cache_[cache_id].link())) {
        return false;
      }
    } else {
      state.set_query_pos(state.query_pos() + 1);
    }
    state.set_node_id(cache_[cache_id].child());
    return true;
  }

  std::size_t louds_pos = louds_.select0(state.node_id()) + 1;
  if (!louds_[louds_pos]) {
    return false;
  }
  state.set_node_id(louds_pos - state.node_id() - 1);
  std::size_t link_id = MARISA_INVALID_LINK_ID;
  do {
    if (link_flags_[state.node_id()]) {
      link_id = update_link_id(link_id, state.node_id());
      const std::size_t prev_query_pos = state.query_pos();
      if (match(agent, get_link(state.node_id(), link_id))) {
        return true;
      } else if (state.query_pos() != prev_query_pos) {
        return false;
      }
    } else if (bases_[state.node_id()] ==
        (UInt8)agent.query()[state.query_pos()]) {
      state.set_query_pos(state.query_pos() + 1);
      return true;
    }
    state.set_node_id(state.node_id() + 1);
    ++louds_pos;
  } while (louds_[louds_pos]);
  return false;
}

std::size_t LoudsTrie::get_cache_id(std::size_t node_id, char label) const {
  return (node_id ^ (node_id << 5) ^ (UInt8)label) & cache_mask_;
}

std::size_t LoudsTrie::get_cache_id(std::size_t node_id) const {
  return node_id & cache_mask_;
}

bool LoudsTrie::match(Agent &agent, std::size_t link) const {
  if (next_trie_.get() != NULL) {
    return next_trie_->match_(agent, link);
  } else {
    return tail_.match(agent, link);
  }
}

bool LoudsTrie::match_(Agent &agent, std::size_t node_id) const {
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);
  MARISA_DEBUG_IF(node_id == 0, MARISA_RANGE_ERROR);

  State &state = agent.state();
  for ( ; ; ) {
    const std::size_t cache_id = get_cache_id(node_id);
    if (node_id == cache_[cache_id].child()) {
      if (cache_[cache_id].extra() != MARISA_INVALID_EXTRA) {
        if (!match(agent, cache_[cache_id].link())) {
          return false;
        }
      } else if (cache_[cache_id].label() ==
          agent.query()[state.query_pos()]) {
        state.set_query_pos(state.query_pos() + 1);
      } else {
        return false;
      }

      node_id = cache_[cache_id].parent();
      if (node_id == 0) {
        return true;
      } else if (state.query_pos() >= agent.query().length()) {
        return false;
      }
      continue;
    }

    if (link_flags_[node_id]) {
      if (next_trie_.get() != NULL) {
        if (!match(agent, get_link(node_id))) {
          return false;
        }
      } else if (!tail_.match(agent, get_link(node_id))) {
        return false;
      }
    } else if (bases_[node_id] == (UInt8)agent.query()[state.query_pos()]) {
      state.set_query_pos(state.query_pos() + 1);
    } else {
      return false;
    }

    if (node_id <= num_l1_nodes_) {
      return true;
    } else if (state.query_pos() >= agent.query().length()) {
      return false;
    }
    node_id = louds_.select1(node_id) - node_id - 1;
  }
}

bool Tail::match(Agent &agent, std::size_t offset) const {
  MARISA_DEBUG_IF(buf_.empty(), MARISA_STATE_ERROR);
  MARISA_DEBUG_IF(agent.state().query_pos() >= agent.query().length(),
      MARISA_BOUND_ERROR);

  State &state = agent.state();
  if (end_flags_.empty()) {
    const char * const ptr = &buf_[offset] - state.query_pos();
    do {
      if (ptr[state.query_pos()] != agent.query()[state.query_pos()]) {
        return false;
      }
      state.set_query_pos(state.query_pos() + 1);
      if (ptr[state.query_pos()] == '\0') {
        return true;
      }
    } while (state.query_pos() < agent.query().length());
    return false;
  } else {
    do {
      if (buf_[offset] != agent.query()[state.query_pos()]) {
        return false;
      }
      state.set_query_pos(state.query_pos() + 1);
      if (end_flags_[offset++]) {
        return true;
      }
    } while (state.query_pos() < agent.query().length());
    return false;
  }
}

*/
<|endoftext|>


<commit_before>// Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use futures::{sync::mpsc, Poll};
use log;
use tokio::{
    self,
    io::{AsyncRead, AsyncWrite},
    prelude::*,
};
use tower_service::Service;

use crate::rules::Rules;
use crate::util::Either;

use super::error::Error;
use super::protocol::{BodyItem, Request, Response};
use super::shutdown::ShutdownMessage;
use super::transport::{Frame, Message, Transport};

/// The service. This is instantiated for each connection to the server.
#[derive(Clone)]
pub struct ButtonService {
    /// Channel to reset the idle timer so the server doesn't shut down.
    shutdown: mpsc::Sender<ShutdownMessage>,
}

impl ButtonService {
    pub fn new(shutdown: mpsc::Sender<ShutdownMessage>) -> Self {
        ButtonService { shutdown }
    }

    pub fn bind<T>(mut self, io: T) -> impl Future<Item = (), Error = Error>
    where
        T: AsyncRead + AsyncWrite,
    {
        let (sink, source) = Transport::new(io).split();

        let mut shutdown = self.shutdown.clone();

        let sink = sink.sink_from_err::<Error>().with(
            move |item| -> Result<_, Error> {
                // Reset the idle timer to keep the server alive while sending
                // back a (potentially long) body.
                drop(shutdown.start_send(ShutdownMessage::ResetIdle));
                Ok(item)
            },
        );

        source
            .from_err::<Error>()
            .and_then(move |input| self.call(input))
            .map(|message| {
                match message {
                    Message::WithoutBody(message) => Either::A(stream::once(
                        Ok(Frame::Message(message, false)),
                    )),
                    Message::WithBody(message, body) => Either::B(
                        stream::once(Ok(Frame::Message(message, true)))
                            .chain(body.map(|chunk| Frame::Body(Some(chunk))))
                            .chain(stream::once(Ok(Frame::Body(None)))),
                    ),
                }
                .from_err::<Error>()
            })
            .flatten()
            .forward(sink)
            .map(|_| ())
    }

    /// Handles a 'build' request.
    fn build(&mut self) -> <Self as Service<Request>>::Future {
        let (tx, rx) = mpsc::channel(1);

        // Send some events.
        tokio::spawn(
            tx.send(BodyItem::BuildEvent(1))
                .and_then(|tx| tx.send(BodyItem::BuildEvent(2)))
                .map_err(|_| ())
                .map(|_| ()),
        );

        let message = Message::WithBody(Ok(()), rx);

        Box::new(future::ok(message))
    }

    /// Handles a 'clean' request.
    fn clean(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles an 'update' request.
    fn update(&mut self, _rules: Rules) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles a 'watch' request.
    fn watch(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles a 'shutdown' request.
    fn shutdown(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(
            self.shutdown
                .clone()
                .send(ShutdownMessage::Shutdown)
                .from_err::<Error>()
                .map(|_| Message::WithoutBody(Ok(()))),
        )
    }
}

impl Service<Request> for ButtonService {
    type Response = Message<Response, mpsc::Receiver<BodyItem>>;
    type Error = Error;
    type Future =
        Box<Future<Item = Self::Response, Error = Self::Error> + Send>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        Ok(Async::Ready(()))
    }

    fn call(&mut self, request: Request) -> Self::Future {
        log::info!("Got request: {:?}", request);

        // We received a request. Keep the server alive. Note that we don't care
        // if `start_send` cannot complete the send. If the channel's buffer is
        // full due to outstanding requests, then sending another reset message
        // isn't necessary.
        drop(self.shutdown.start_send(ShutdownMessage::ResetIdle));

        match request {
            Request::Build => self.build(),
            Request::Clean => self.clean(),
            Request::Update(rules) => self.update(rules),
            Request::Watch => self.watch(),
            Request::Shutdown => self.shutdown(),
        }
    }
}
<commit_msg>Fix warning<commit_after>// Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use futures::{sync::mpsc, Poll};
use log;
use tokio::{
    self,
    io::{AsyncRead, AsyncWrite},
    prelude::*,
};
use tower_service::Service;

use crate::rules::Rules;
use crate::util::Either;

use super::error::Error;
use super::protocol::{BodyItem, Request, Response};
use super::shutdown::ShutdownMessage;
use super::transport::{Frame, Message, Transport};

/// The service. This is instantiated for each connection to the server.
#[derive(Clone)]
pub struct ButtonService {
    /// Channel to reset the idle timer so the server doesn't shut down.
    shutdown: mpsc::Sender<ShutdownMessage>,
}

impl ButtonService {
    pub fn new(shutdown: mpsc::Sender<ShutdownMessage>) -> Self {
        ButtonService { shutdown }
    }

    pub fn bind<T>(mut self, io: T) -> impl Future<Item = (), Error = Error>
    where
        T: AsyncRead + AsyncWrite,
    {
        let (sink, source) = Transport::new(io).split();

        let mut shutdown = self.shutdown.clone();

        let sink = sink.sink_from_err::<Error>().with(
            move |item| -> Result<_, Error> {
                // Reset the idle timer to keep the server alive while sending
                // back a (potentially long) body.
                drop(shutdown.start_send(ShutdownMessage::ResetIdle));
                Ok(item)
            },
        );

        source
            .from_err::<Error>()
            .and_then(move |input| self.call(input))
            .map(|message| {
                match message {
                    Message::WithoutBody(message) => Either::A(stream::once(
                        Ok(Frame::Message(message, false)),
                    )),
                    Message::WithBody(message, body) => Either::B(
                        stream::once(Ok(Frame::Message(message, true)))
                            .chain(body.map(|chunk| Frame::Body(Some(chunk))))
                            .chain(stream::once(Ok(Frame::Body(None)))),
                    ),
                }
                .from_err::<Error>()
            })
            .flatten()
            .forward(sink)
            .map(|_| ())
    }

    /// Handles a 'build' request.
    fn build(&mut self) -> <Self as Service<Request>>::Future {
        let (tx, rx) = mpsc::channel(1);

        // Send some events.
        tokio::spawn(
            tx.send(BodyItem::BuildEvent(1))
                .and_then(|tx| tx.send(BodyItem::BuildEvent(2)))
                .map_err(|_| ())
                .map(|_| ()),
        );

        let message = Message::WithBody(Ok(()), rx);

        Box::new(future::ok(message))
    }

    /// Handles a 'clean' request.
    fn clean(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles an 'update' request.
    fn update(&mut self, _rules: Rules) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles a 'watch' request.
    fn watch(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(future::ok(Message::WithoutBody(Ok(()))))
    }

    /// Handles a 'shutdown' request.
    fn shutdown(&mut self) -> <Self as Service<Request>>::Future {
        Box::new(
            self.shutdown
                .clone()
                .send(ShutdownMessage::Shutdown)
                .from_err::<Error>()
                .map(|_| Message::WithoutBody(Ok(()))),
        )
    }
}

impl Service<Request> for ButtonService {
    type Response = Message<Response, mpsc::Receiver<BodyItem>>;
    type Error = Error;
    type Future =
        Box<dyn Future<Item = Self::Response, Error = Self::Error> + Send>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        Ok(Async::Ready(()))
    }

    fn call(&mut self, request: Request) -> Self::Future {
        log::info!("Got request: {:?}", request);

        // We received a request. Keep the server alive. Note that we don't care
        // if `start_send` cannot complete the send. If the channel's buffer is
        // full due to outstanding requests, then sending another reset message
        // isn't necessary.
        drop(self.shutdown.start_send(ShutdownMessage::ResetIdle));

        match request {
            Request::Build => self.build(),
            Request::Clean => self.clean(),
            Request::Update(rules) => self.update(rules),
            Request::Watch => self.watch(),
            Request::Shutdown => self.shutdown(),
        }
    }
}
<|endoftext|>


<commit_before>use std::sync::Arc;

use bsdf::{BSDF, BxDF, LambertianReflection, OrenNayar};
use spectrum::Spectrum;
use material::{Material, TransportMode};
use interaction::SurfaceInteraction;
use texture::{Texture, ConstantTexture, CheckerboardTexture};

pub struct MatteMaterial {
    kd: Arc<Texture<Spectrum> + Sync + Send>,
    sigma: f32,
}

impl MatteMaterial {
    pub fn new(r: Spectrum, sigma: f32) -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(ConstantTexture::new(r)),
            sigma: sigma,
        }
    }

    pub fn checkerboard(sigma: f32) -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(CheckerboardTexture::bw()),
            sigma: sigma,
        }
    }

    pub fn bsdf(&self, si: &SurfaceInteraction) -> BSDF {
        let mut bxdfs: Vec<Box<BxDF + Send + Sync>> = Vec::new();
        let r = self.kd.evaluate(si);
        if self.sigma == 0.0 {
            bxdfs.push(Box::new(LambertianReflection::new(r)));
        } else {
            bxdfs.push(Box::new(OrenNayar::new(r, self.sigma)));
        }

        BSDF::new(si, 1.5, bxdfs)
    }
}

impl Material for MatteMaterial {
    fn compute_scattering_functions(&self,
                                    si: &mut SurfaceInteraction,
                                    _mode: TransportMode,
                                    _allow_multiple_lobes: bool) {
        si.bsdf = Some(Arc::new(self.bsdf(si)));
    }
}

impl Default for MatteMaterial {
    fn default() -> Self {
        MatteMaterial::new(Spectrum::grey(0.5), 0.0)
    }
}
<commit_msg>Add more constructors for MatteMaterial<commit_after>use std::sync::Arc;
use std::path::Path;

use bsdf::{BSDF, BxDF, LambertianReflection, OrenNayar};
use spectrum::Spectrum;
use material::{Material, TransportMode};
use interaction::SurfaceInteraction;
use texture::{Texture, ConstantTexture, CheckerboardTexture, ImageTexture, UVTexture};

pub struct MatteMaterial {
    kd: Arc<Texture<Spectrum> + Sync + Send>,
    sigma: f32,
}

impl MatteMaterial {
    pub fn new(r: Spectrum, sigma: f32) -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(ConstantTexture::new(r)),
            sigma: sigma,
        }
    }

    pub fn new_uv_texture() -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(UVTexture::new()),
            sigma: 0.0,
        }
    }

    pub fn new_image(kd: &str) -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(ImageTexture::new(Path::new(kd))),
            sigma: 0.0,
        }
    }

    pub fn checkerboard(sigma: f32) -> MatteMaterial {
        MatteMaterial {
            kd: Arc::new(CheckerboardTexture::bw()),
            sigma: sigma,
        }
    }

    pub fn bsdf(&self, si: &SurfaceInteraction) -> BSDF {
        let mut bxdfs: Vec<Box<BxDF + Send + Sync>> = Vec::new();
        let r = self.kd.evaluate(si);
        if self.sigma == 0.0 {
            bxdfs.push(Box::new(LambertianReflection::new(r)));
        } else {
            bxdfs.push(Box::new(OrenNayar::new(r, self.sigma)));
        }

        BSDF::new(si, 1.5, bxdfs)
    }
}

impl Material for MatteMaterial {
    fn compute_scattering_functions(&self,
                                    si: &mut SurfaceInteraction,
                                    _mode: TransportMode,
                                    _allow_multiple_lobes: bool) {
        si.bsdf = Some(Arc::new(self.bsdf(si)));
    }
}

impl Default for MatteMaterial {
    fn default() -> Self {
        MatteMaterial::new(Spectrum::grey(0.5), 0.0)
    }
}
<|endoftext|>


<commit_before>pub const BIOS_START_ADDRESS: usize = 0x80000000;
pub const NUM_REGISTERS: usize = 4;
pub const MAX_ADDRESS: usize = 0xFFFFFFFF;
pub const NUM_IVT_ENTRIES: usize = 1;
pub const NUM_FLAGS: usize = 1;
pub const REGISTERS_START_ADDRESS: usize = MAX_ADDRESS - 4 * NUM_REGISTERS + 1;
pub const IVT_RETURN_ADDRESS: usize = REGISTERS_START_ADDRESS - 4;
pub const IVT_START_ADDRESS: usize = IVT_RETURN_ADDRESS - 4 * NUM_IVT_ENTRIES;
pub const FLAGS_START_ADDRESS: usize = IVT_START_ADDRESS - 4 * NUM_FLAGS;

pub const FLAG0_HALTED: usize = 0;
pub const FLAG0_BIOS_DONE: usize = 1;
<commit_msg>refactor(address): Update for new memory design<commit_after>pub const BIOS_START_ADDRESS: usize = 0x40000000;
pub const NUM_REGISTERS: usize = 4;
pub const MAX_ADDRESS: usize = 0x8FFFFFFF;
pub const NUM_IVT_ENTRIES: usize = 1;
pub const NUM_FLAGS: usize = 1;
pub const FLAGS_START_ADDRESS: usize = MAX_ADDRESS - NUM_FLAGS;
pub const IVT_START_ADDRESS: usize = FLAGS_START_ADDRESS - NUM_IVT_ENTRIES;
pub const REGISTERS_START_ADDRESS: usize = IVT_START_ADDRESS - NUM_REGISTERS;
pub const STACK_POINTER_ADDRESS: usize = REGISTERS_START_ADDRESS - 1;
pub const CONTROLS_ADDRESS: usize = STACK_POINTER_ADDRESS;

pub const FLAG0_HALTED: usize = 0;
pub const FLAG0_BIOS_DONE: usize = 1;
<|endoftext|>


<commit_before>#[macro_use]
extern crate log;
extern crate env_logger;

extern crate osmpbfreader;
extern crate rustc_serialize;
extern crate docopt;
extern crate mimirsbrunn;

use std::collections::HashSet;

use std::collections::BTreeMap;
use osmpbfreader::{OsmObj, OsmId};

pub type AdminsMap = BTreeMap<OsmId, mimirsbrunn::Admin>;

#[derive(RustcDecodable, Debug)]
struct Args {
    flag_input: String,
    flag_level: Vec<u32>,
}

static USAGE: &'static str = "
Usage:
    osm2mimir --input=<pbf-file> --level=<admin-level>...

Options:
    -h, --help                               Show this message.
    -i <pbf-file>, --input=<pbf-file>        OSM PBF file.
    -l <admin-level>, --level=<admin-level>  Admin levels to keep.
";

fn get_osm_id(obj: &OsmObj) -> OsmId {
    match *obj {
        OsmObj::Node(ref node) => OsmId::Node(node.id),
        OsmObj::Way(ref way) => OsmId::Way(way.id),
        OsmObj::Relation(ref rel) => OsmId::Relation(rel.id),
    }
}

fn update_coordinates(filename: &String, admins: &mut AdminsMap) {
    if admins.is_empty() {
        return;
    }
    // load coord for administratives regions
    let path = std::path::Path::new(&filename);
    let r = std::fs::File::open(&path).unwrap();
    let mut pbf = osmpbfreader::OsmPbfReader::new(r);
    for obj in pbf.iter() {
        if let osmpbfreader::OsmObj::Node(ref node) = obj {
            let mut adm = match admins.get_mut(&get_osm_id(&obj)) {
                Some(val) => val,
                None => continue,
            };
            adm.coord.lat = node.lat;
            adm.coord.lon = node.lon;
        }
    }
}

fn administartive_regions(filename: &String, levels: &HashSet<u32>) -> AdminsMap {
    let mut administrative_regions = AdminsMap::new();
    let path = std::path::Path::new(&filename);
    let r = std::fs::File::open(&path).unwrap();
    let mut pbf = osmpbfreader::OsmPbfReader::new(r);
    // load administratives regions
    for obj in pbf.iter() {
        if let osmpbfreader::OsmObj::Relation(relation) = obj {
            // not administartive region
            if !relation.tags
                        .get("boundary")
                        .map(|s| s == "administrative")
                        .unwrap_or(false) {
                continue;
            }
            // admininstrative region without coordinates
            let admin_centre = match relation.refs.iter().find(|rf| rf.role == "admin_centre") {
                Some(val) => val.member,
                None => {
                    info!("adminstrative regione without coordinates for relation {}.",
                          relation.id);
                    continue;
                }
            };
            let level = relation.tags
                                .get("admin_level")
                                .and_then(|s| s.parse().ok());
            let level = match level {
                None => {
                    info!("invalid admin_level for relation {}: admin_level {:?}",
                          relation.id,
                          relation.tags.get("admin_level"));
                    continue;
                }
                Some(ref l) if !levels.contains(&l) => {
                    info!("admin_level ignored for relation {}:  admin_level {:?}.",
                          relation.id,
                          level);
                    continue;
                }
                Some(l) => l,
            };
            // administrative region with name ?
            let name = match relation.tags.get("name") {
                Some(val) => val,
                None => {
                    info!("adminstrative regione without name for relation {}:  admin_level {} \
                           ignored .",
                          relation.id,
                          level);
                    continue;
                }
            };
            let admin_id = match relation.tags.get("ref:INSEE") {
                Some(val) => format!("admin:fr:{}", val),
                None => format!("admin:osm:{}", relation.id),
            };
            let zip_code = match relation.tags.get("addr:postcode") {
                Some(val) => &val[..],
                None => "",
            };
            let admin = mimirsbrunn::Admin {
                id: admin_id,
                level: level,
                name: name.to_string(),
                zip_code: zip_code.to_string(),
                // TODO weight value ?
                weight: 1,
                coord: mimirsbrunn::Coord {
                    lat: 0.0,
                    lon: 0.0,
                },
            };
            administrative_regions.insert(admin_centre, admin);
        }
    }
    return administrative_regions;
}

fn main() {
    env_logger::init().unwrap();
    debug!("importing adminstrative region into Mimir");
    let args: Args = docopt::Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| e.exit());
    let levels = args.flag_level.iter().cloned().collect();
    let mut res = administartive_regions(&args.flag_input, &levels);
    update_coordinates(&args.flag_input, &mut res);
}
<commit_msg>mimirsbrunn: refacto<commit_after>#[macro_use]
extern crate log;
extern crate env_logger;
extern crate osmpbfreader;
extern crate rustc_serialize;
extern crate docopt;
extern crate mimirsbrunn;

use std::collections::HashSet;
use std::collections::BTreeMap;
use osmpbfreader::{OsmObj, OsmId};

pub type AdminsMap = BTreeMap<OsmId, mimirsbrunn::Admin>;

#[derive(RustcDecodable, Debug)]
struct Args {
    flag_input: String,
    flag_level: Vec<u32>,
}

static USAGE: &'static str = "
Usage:
    osm2mimir --input=<pbf-file> --level=<admin-level>...

Options:
    -h, --help                               Show this message.
    -i <pbf-file>, --input=<pbf-file>        OSM PBF file.
    -l <admin-level>, --level=<admin-level>  Admin levels to keep.
";

fn get_osm_id(obj: &OsmObj) -> OsmId {
    match *obj {
        OsmObj::Node(ref node) => OsmId::Node(node.id),
        OsmObj::Way(ref way) => OsmId::Way(way.id),
        OsmObj::Relation(ref rel) => OsmId::Relation(rel.id),
    }
}

fn update_coordinates(filename: &String, admins: &mut AdminsMap) {
    if admins.is_empty() {
        return;
    }
    // load coord for administratives regions
    let path = std::path::Path::new(&filename);
    let r = std::fs::File::open(&path).unwrap();
    let mut pbf = osmpbfreader::OsmPbfReader::new(r);
    for obj in pbf.iter() {
        if let osmpbfreader::OsmObj::Node(ref node) = obj {
            let mut adm = match admins.get_mut(&get_osm_id(&obj)) {
                Some(val) => val,
                None => continue,
            };
            adm.coord.lat = node.lat;
            adm.coord.lon = node.lon;
        }
    }
}

fn administartive_regions(filename: &String, levels: &HashSet<u32>) -> AdminsMap {
    let mut administrative_regions = AdminsMap::new();
    let path = std::path::Path::new(&filename);
    let r = std::fs::File::open(&path).unwrap();
    let mut pbf = osmpbfreader::OsmPbfReader::new(r);
    // load administratives regions
    for obj in pbf.iter() {
        if let osmpbfreader::OsmObj::Relation(relation) = obj {
            // not administartive region
            if !relation.tags
                        .get("boundary")
                        .map(|s| s == "administrative")
                        .unwrap_or(false) {
                continue;
            }
            // admininstrative region without coordinates
            let admin_centre = match relation.refs.iter().find(|rf| rf.role == "admin_centre") {
                Some(val) => val.member,
                None => {
                    info!("adminstrative regione without coordinates for relation {}.",
                          relation.id);
                    continue;
                }
            };
            let level = relation.tags
                                .get("admin_level")
                                .and_then(|s| s.parse().ok());
            let level = match level {
                None => {
                    info!("invalid admin_level for relation {}: admin_level {:?}",
                          relation.id,
                          relation.tags.get("admin_level"));
                    continue;
                }
                Some(ref l) if !levels.contains(&l) => continue,
                Some(l) => l,
            };
            // administrative region with name ?
            let name = match relation.tags.get("name") {
                Some(val) => val,
                None => {
                    info!("adminstrative regione without name for relation {}:  admin_level {} \
                           ignored .",
                          relation.id,
                          level);
                    continue;
                }
            };
            let admin_id = match relation.tags.get("ref:INSEE") {
                Some(val) => format!("admin:fr:{}", val),
                None => format!("admin:osm:{}", relation.id),
            };
            let zip_code = match relation.tags.get("addr:postcode") {
                Some(val) => &val[..],
                None => "",
            };
            let admin = mimirsbrunn::Admin {
                id: admin_id,
                level: level,
                name: name.to_string(),
                zip_code: zip_code.to_string(),
                // TODO weight value ?
                weight: 1,
                coord: mimirsbrunn::Coord {
                    lat: 0.0,
                    lon: 0.0,
                },
            };
            administrative_regions.insert(admin_centre, admin);
        }
    }
    return administrative_regions;
}

fn main() {
    env_logger::init().unwrap();
    debug!("importing adminstrative region into Mimir");
    let args: Args = docopt::Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| e.exit());
    let levels = args.flag_level.iter().cloned().collect();
    let mut res = administartive_regions(&args.flag_input, &levels);
    update_coordinates(&args.flag_input, &mut res);
}
<|endoftext|>


<commit_before>use std::collections::BTreeMap;
use rustc_serialize::json::{ToJson, Json};
use postgres;
use uuid::Uuid;
use std::fmt;
use chrono::{NaiveDateTime, UTC, DateTime};

use apple_music;
use youtube;
use youtube::HasThumbnail;
use soundcloud;
use spotify;
use error::Error;
use super::{conn, Model};
use model::provider::Provider;
use model::state::State;
use model::enclosure::Enclosure;

static PROPS: [&'static str; 12]  = ["id",
                                     "provider",
                                     "identifier",
                                     "url",
                                     "title",
                                     "description",
                                     "thumbnail_url",
                                     "artwork_url",
                                     "published_at",
                                     "created_at",
                                     "updated_at",
                                     "state"];

#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct Playlist {
    pub id:            Uuid,
    pub provider:      Provider,
    pub identifier:    String,
    pub url:           String,
    pub title:         String,
    pub description:   Option<String>,
    pub thumbnail_url: Option<String>,
    pub artwork_url:   Option<String>,
    pub published_at:  NaiveDateTime,
    pub created_at:    NaiveDateTime,
    pub updated_at:    NaiveDateTime,
    pub state:         State,
}

impl PartialEq for Playlist {
    fn eq(&self, p: &Playlist) -> bool {
        return self.identifier == p.identifier && self.provider == p.provider
    }
}

impl ToJson for Playlist {
    fn to_json(&self) -> Json {
        let published_at = DateTime::<UTC>::from_utc(self.published_at, UTC);
        let created_at   = DateTime::<UTC>::from_utc(self.created_at  , UTC);
        let updated_at   = DateTime::<UTC>::from_utc(self.updated_at  , UTC);
        let mut d = BTreeMap::new();
        d.insert("id".to_string()           , self.id.to_string().to_json());
        d.insert("provider".to_string()     , self.provider.to_json());
        d.insert("identifier".to_string()   , self.identifier.to_json());
        d.insert("url".to_string()          , self.url.to_json());
        d.insert("title".to_string()        , self.title.to_json());
        d.insert("description".to_string()  , self.description.to_json());
        d.insert("thumbnail_url".to_string(), self.thumbnail_url.to_json());
        d.insert("artwork_url".to_string()  , self.artwork_url.to_json());
        d.insert("published_at".to_string() , published_at.to_rfc3339().to_json());
        d.insert("created_at".to_string()   , created_at.to_rfc3339().to_json());
        d.insert("updated_at".to_string()   , updated_at.to_rfc3339().to_json());
        d.insert("state".to_string()        , self.state.to_json());
        Json::Object(d)
    }
}

impl fmt::Display for Playlist {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.provider, self.identifier)
    }
}

impl Model for Playlist {
    fn table_name() -> String { "playlists".to_string() }
    fn props_str(prefix: &str) -> String {
        PROPS
            .iter()
            .map(|&p| format!("{}{}", prefix, p))
            .collect::<Vec<String>>().join(",")
    }
    fn rows_to_items(rows: postgres::rows::Rows) -> Vec<Playlist> {
        let mut playlists = Vec::new();
        for row in rows.iter() {
            let playlist = Playlist {
                id:            row.get(0),
                provider:      Provider::new(row.get(1)),
                identifier:    row.get(2),
                url:           row.get(3),
                title:         row.get(4),
                description:   row.get(5),
                thumbnail_url: row.get(6),
                artwork_url:   row.get(7),
                published_at:  row.get(8),
                created_at:    row.get(9),
                updated_at:    row.get(10),
                state:         State::new(row.get(11)),
            };
            playlists.push(playlist)
        }
        playlists
    }

    fn create(&self) -> Result<Playlist, Error> {
        let conn = try!(conn());
        let stmt = try!(conn.prepare("INSERT INTO playlists (provider, identifier, url, title)
                                 VALUES ($1, $2, $3, $4) RETURNING id"));
        let rows = try!(stmt.query(&[&self.provider.to_string(), &self.identifier, &self.url, &self.title]));
        let mut playlist = self.clone();
        for row in rows.iter() {
            playlist.id = row.get(0);
        }
        Ok(playlist)
    }

    fn save(&mut self) -> Result<(), Error> {
        self.updated_at = UTC::now().naive_utc();
        let conn = conn().unwrap();
        let stmt = conn.prepare("UPDATE playlists SET
                                 provider      = $2,
                                 identifier    = $3,
                                 url           = $4,
                                 title         = $5,
                                 description   = $6,
                                 thumbnail_url = $7,
                                 artwork_url   = $8,
                                 published_at  = $9,
                                 created_at    = $10,
                                 updated_at    = $11,
                                 state         = $12
                                 WHERE id = $1").unwrap();
        let result = stmt.query(&[&self.id,
                                  &self.provider.to_string(),
                                  &self.identifier,
                                  &self.url,
                                  &self.title,
                                  &self.description,
                                  &self.thumbnail_url,
                                  &self.artwork_url,
                                  &self.published_at,
                                  &self.created_at,
                                  &self.updated_at,
                                  &self.state.to_string(),
        ]);
        match result {
            Ok(_)  => Ok(()),
            Err(_) => Err(Error::Unexpected),
        }
    }
}

impl Enclosure for Playlist {
    fn new(provider: Provider, identifier: String) -> Playlist {
        Playlist {
            id:            Uuid::new_v4(),
            provider:      provider,
            identifier:    identifier,
            url:           "".to_string(),
            title:         "".to_string(),
            description:   None,
            thumbnail_url: None,
            artwork_url:   None,
            published_at:  UTC::now().naive_utc(),
            created_at:    UTC::now().naive_utc(),
            updated_at:    UTC::now().naive_utc(),
            state:         State::Alive,
        }
    }
    fn find_by_entry_id(entry_id: Uuid) -> Vec<Playlist> {
        let conn = conn().unwrap();
        let stmt = conn.prepare(
            &format!("SELECT {} FROM playlists p LEFT JOIN playlist_entries pe
                        ON p.id = pe.playlist_id
                        WHERE pe.entry_id = $1
                        ORDER BY p.published_at DESC",
                     Playlist::props_str("p."))).unwrap();
        let rows = stmt.query(&[&entry_id]).unwrap();
        Playlist::rows_to_items(rows)
    }
}

impl Playlist {
    pub fn from_yt_playlist(playlist: &youtube::Playlist) -> Playlist {
        Playlist::new(Provider::YouTube, (*playlist).id.to_string())
            .update_with_yt_playlist(playlist)
            .clone()
    }

    pub fn from_sp_playlist(playlist: &spotify::Playlist) -> Playlist {
        Playlist::new(Provider::Spotify, (*playlist).id.to_string())
            .update_with_sp_playlist(playlist)
            .clone()
    }

    pub fn from_sc_playlist(playlist: &soundcloud::Playlist) -> Playlist {
        Playlist::new(Provider::SoundCloud, (*playlist).id.to_string())
            .update_with_sc_playlist(playlist)
            .clone()
    }

    pub fn from_am_playlist(playlist: &apple_music::Playlist) -> Playlist {
        Playlist::new(Provider::AppleMusic, (*playlist).id.to_string())
            .update_with_am_playlist(playlist)
            .clone()
    }

    pub fn update_with_yt_playlist(&mut self, playlist: &youtube::Playlist) -> &mut Playlist {
        self.provider      = Provider::YouTube;
        self.identifier    = playlist.id.to_string();
        self.url           = format!("https://www.youtube.com/watch/?v={}", playlist.id);
        self.title         = playlist.snippet.title.to_string();
        self.description   = Some(playlist.snippet.description.to_string());
        self.thumbnail_url = playlist.snippet.get_thumbnail_url();
        self.artwork_url   = playlist.snippet.get_artwork_url();
        self.state         = State::Alive;
        match DateTime::parse_from_rfc3339(&playlist.snippet.publishedAt) {
            Ok(published_at) => self.published_at = published_at.naive_utc(),
            Err(_)           => (),
        }
        self
    }

    pub fn update_with_sp_playlist(&mut self, playlist: &spotify::Playlist) -> &mut Playlist {
        self.provider       = Provider::Spotify;
        self.identifier     = playlist.id.to_string();
        self.url            = playlist.uri.clone();
        self.title          = playlist.name.clone();
        self.description    = None;
        self.state          = State::Alive;
        self.published_at   = UTC::now().naive_utc();
        if playlist.images.len() > 0 {
            self.artwork_url   = Some(playlist.images[0].url.clone());
            self.thumbnail_url = Some(playlist.images[0].url.clone());
        }
        if playlist.images.len() > 1 {
            self.thumbnail_url = Some(playlist.images[1].url.clone());
        }
        self
    }

    pub fn update_with_sc_playlist(&mut self, playlist: &soundcloud::Playlist) -> &mut Playlist {
        self.provider      = Provider::SoundCloud;
        self.identifier    = playlist.id.to_string();
        self.url           = playlist.permalink_url.to_string();
        self.title         = playlist.title.to_string();
        self.description   = None;
        self.thumbnail_url = playlist.artwork_url.clone();
        self.artwork_url   = playlist.artwork_url.clone();
        self.state         = State::Alive;
        match DateTime::parse_from_str(&playlist.created_at, "%Y/%m/%d %H:%M:%S %z") {
            Ok(published_at) => self.published_at = published_at.naive_utc(),
            Err(_)           => (),
        }
        self
    }

    pub fn update_with_am_playlist(&mut self, playlist: &apple_music::Playlist) -> &mut Playlist {
        self.provider      = Provider::AppleMusic;
        self.identifier    = playlist.id.to_string();
        self.url           = playlist.music_url.to_string();
        self.title         = playlist.title.to_string();
        self.description   = Some(playlist.description.to_string());
        self.thumbnail_url = Some(playlist.artwork_url.to_string());
        self.artwork_url   = Some(playlist.artwork_url.to_string());
        self.state         = State::Alive;
        self
    }

    pub fn disable(&mut self) -> &mut Playlist {
        self.state = State::Dead;
        self
    }

    pub fn delete(&self) -> Result<(), Error> {
        let conn = conn().unwrap();
        let stmt = conn.prepare("DELETE FROM playlists WHERE id=$1").unwrap();
        let result = stmt.query(&[&self.id]);
        match result {
            Ok(_)  => Ok(()),
            Err(_) => Err(Error::Unexpected)
        }
    }
}

#[cfg(test)]
mod test {
    use model::enclosure::Enclosure;
    use model::Model;
    use super::Playlist;
    use Provider;
    #[test]
    fn test_new() {
        let playlist = Playlist::new(Provider::YouTube,
                                     "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX".to_string());
        assert_eq!(playlist.provider, Provider::YouTube);
        assert_eq!(&playlist.identifier, "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX")
    }
    #[test]
    fn test_find_of_create() {
        let identifier = "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX".to_string();
        let result     = Playlist::find_or_create(Provider::YouTube, identifier);
        assert!(result.is_ok());
    }
    #[test]
    fn test_delete() {
        let identifier = "test_delete".to_string();
        let playlist   = Playlist::find_or_create(Provider::YouTube, identifier).unwrap();
        let result     = playlist.delete();
        assert!(result.is_ok());
    }
    #[test]
    fn test_save() {
        let id = "test_save";
        let mut playlist = Playlist::find_or_create(Provider::YouTube, id.to_string()).unwrap();
        playlist.title = "title".to_string();
        let result = playlist.save();
        assert!(result.is_ok());
        let playlist = Playlist::find_or_create(Provider::YouTube, id.to_string()).unwrap();
        assert_eq!(&playlist.title, "title");
    }
}
<commit_msg>Add owner_id, owner_name properties to model::Playlist struct<commit_after>use std::collections::BTreeMap;
use rustc_serialize::json::{ToJson, Json};
use postgres;
use uuid::Uuid;
use std::fmt;
use chrono::{NaiveDateTime, UTC, DateTime};

use apple_music;
use youtube;
use youtube::HasThumbnail;
use soundcloud;
use spotify;
use error::Error;
use super::{conn, Model};
use model::provider::Provider;
use model::state::State;
use model::enclosure::Enclosure;

static PROPS: [&'static str; 14]  = ["id",
                                     "provider",
                                     "identifier",
                                     "owner_id",
                                     "owner_name",
                                     "url",
                                     "title",
                                     "description",
                                     "thumbnail_url",
                                     "artwork_url",
                                     "published_at",
                                     "created_at",
                                     "updated_at",
                                     "state"];

#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
pub struct Playlist {
    pub id:            Uuid,
    pub provider:      Provider,
    pub identifier:    String,
    pub owner_id:      Option<String>,
    pub owner_name:    Option<String>,
    pub url:           String,
    pub title:         String,
    pub description:   Option<String>,
    pub thumbnail_url: Option<String>,
    pub artwork_url:   Option<String>,
    pub published_at:  NaiveDateTime,
    pub created_at:    NaiveDateTime,
    pub updated_at:    NaiveDateTime,
    pub state:         State,
}

impl PartialEq for Playlist {
    fn eq(&self, p: &Playlist) -> bool {
        return self.identifier == p.identifier && self.provider == p.provider
    }
}

impl ToJson for Playlist {
    fn to_json(&self) -> Json {
        let published_at = DateTime::<UTC>::from_utc(self.published_at, UTC);
        let created_at   = DateTime::<UTC>::from_utc(self.created_at  , UTC);
        let updated_at   = DateTime::<UTC>::from_utc(self.updated_at  , UTC);
        let mut d = BTreeMap::new();
        d.insert("id".to_string()           , self.id.to_string().to_json());
        d.insert("provider".to_string()     , self.provider.to_json());
        d.insert("identifier".to_string()   , self.identifier.to_json());
        d.insert("owner_id".to_string()     , self.owner_id.to_json());
        d.insert("owner_name".to_string()   , self.owner_name.to_json());
        d.insert("url".to_string()          , self.url.to_json());
        d.insert("title".to_string()        , self.title.to_json());
        d.insert("description".to_string()  , self.description.to_json());
        d.insert("thumbnail_url".to_string(), self.thumbnail_url.to_json());
        d.insert("artwork_url".to_string()  , self.artwork_url.to_json());
        d.insert("published_at".to_string() , published_at.to_rfc3339().to_json());
        d.insert("created_at".to_string()   , created_at.to_rfc3339().to_json());
        d.insert("updated_at".to_string()   , updated_at.to_rfc3339().to_json());
        d.insert("state".to_string()        , self.state.to_json());
        Json::Object(d)
    }
}

impl fmt::Display for Playlist {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.provider, self.identifier)
    }
}

impl Model for Playlist {
    fn table_name() -> String { "playlists".to_string() }
    fn props_str(prefix: &str) -> String {
        PROPS
            .iter()
            .map(|&p| format!("{}{}", prefix, p))
            .collect::<Vec<String>>().join(",")
    }
    fn rows_to_items(rows: postgres::rows::Rows) -> Vec<Playlist> {
        let mut playlists = Vec::new();
        for row in rows.iter() {
            let playlist = Playlist {
                id:            row.get(0),
                provider:      Provider::new(row.get(1)),
                identifier:    row.get(2),
                owner_id:      row.get(3),
                owner_name:    row.get(4),
                url:           row.get(5),
                title:         row.get(6),
                description:   row.get(7),
                thumbnail_url: row.get(8),
                artwork_url:   row.get(9),
                published_at:  row.get(10),
                created_at:    row.get(11),
                updated_at:    row.get(12),
                state:         State::new(row.get(13)),
            };
            playlists.push(playlist)
        }
        playlists
    }

    fn create(&self) -> Result<Playlist, Error> {
        let conn = try!(conn());
        let stmt = try!(conn.prepare("INSERT INTO playlists (provider, identifier, url, title)
                                 VALUES ($1, $2, $3, $4) RETURNING id"));
        let rows = try!(stmt.query(&[&self.provider.to_string(), &self.identifier, &self.url, &self.title]));
        let mut playlist = self.clone();
        for row in rows.iter() {
            playlist.id = row.get(0);
        }
        Ok(playlist)
    }

    fn save(&mut self) -> Result<(), Error> {
        self.updated_at = UTC::now().naive_utc();
        let conn = conn().unwrap();
        let stmt = conn.prepare("UPDATE playlists SET
                                 provider      = $2,
                                 identifier    = $3,
                                 owner_id      = $4,
                                 owner_name    = $5,
                                 url           = $6,
                                 title         = $7,
                                 description   = $8,
                                 thumbnail_url = $9,
                                 artwork_url   = $10,
                                 published_at  = $11,
                                 created_at    = $12,
                                 updated_at    = $13,
                                 state         = $14
                                 WHERE id = $1").unwrap();
        let result = stmt.query(&[&self.id,
                                  &self.provider.to_string(),
                                  &self.identifier,
                                  &self.owner_id,
                                  &self.owner_name,
                                  &self.url,
                                  &self.title,
                                  &self.description,
                                  &self.thumbnail_url,
                                  &self.artwork_url,
                                  &self.published_at,
                                  &self.created_at,
                                  &self.updated_at,
                                  &self.state.to_string(),
        ]);
        match result {
            Ok(_)  => Ok(()),
            Err(_) => Err(Error::Unexpected),
        }
    }
}

impl Enclosure for Playlist {
    fn new(provider: Provider, identifier: String) -> Playlist {
        Playlist {
            id:            Uuid::new_v4(),
            provider:      provider,
            identifier:    identifier,
            owner_id:      None,
            owner_name:    None,
            url:           "".to_string(),
            title:         "".to_string(),
            description:   None,
            thumbnail_url: None,
            artwork_url:   None,
            published_at:  UTC::now().naive_utc(),
            created_at:    UTC::now().naive_utc(),
            updated_at:    UTC::now().naive_utc(),
            state:         State::Alive,
        }
    }
    fn find_by_entry_id(entry_id: Uuid) -> Vec<Playlist> {
        let conn = conn().unwrap();
        let stmt = conn.prepare(
            &format!("SELECT {} FROM playlists p LEFT JOIN playlist_entries pe
                        ON p.id = pe.playlist_id
                        WHERE pe.entry_id = $1
                        ORDER BY p.published_at DESC",
                     Playlist::props_str("p."))).unwrap();
        let rows = stmt.query(&[&entry_id]).unwrap();
        Playlist::rows_to_items(rows)
    }
}

impl Playlist {
    pub fn from_yt_playlist(playlist: &youtube::Playlist) -> Playlist {
        Playlist::new(Provider::YouTube, (*playlist).id.to_string())
            .update_with_yt_playlist(playlist)
            .clone()
    }

    pub fn from_sp_playlist(playlist: &spotify::Playlist) -> Playlist {
        Playlist::new(Provider::Spotify, (*playlist).id.to_string())
            .update_with_sp_playlist(playlist)
            .clone()
    }

    pub fn from_sc_playlist(playlist: &soundcloud::Playlist) -> Playlist {
        Playlist::new(Provider::SoundCloud, (*playlist).id.to_string())
            .update_with_sc_playlist(playlist)
            .clone()
    }

    pub fn from_am_playlist(playlist: &apple_music::Playlist) -> Playlist {
        Playlist::new(Provider::AppleMusic, (*playlist).id.to_string())
            .update_with_am_playlist(playlist)
            .clone()
    }

    pub fn update_with_yt_playlist(&mut self, playlist: &youtube::Playlist) -> &mut Playlist {
        self.provider      = Provider::YouTube;
        self.identifier    = playlist.id.to_string();
        self.owner_id      = Some(playlist.snippet.channelId.to_string());
        self.owner_name    = Some(playlist.snippet.channelTitle.to_string());
        self.url           = format!("https://www.youtube.com/watch/?v={}", playlist.id);
        self.title         = playlist.snippet.title.to_string();
        self.description   = Some(playlist.snippet.description.to_string());
        self.thumbnail_url = playlist.snippet.get_thumbnail_url();
        self.artwork_url   = playlist.snippet.get_artwork_url();
        self.state         = State::Alive;
        match DateTime::parse_from_rfc3339(&playlist.snippet.publishedAt) {
            Ok(published_at) => self.published_at = published_at.naive_utc(),
            Err(_)           => (),
        }
        self
    }

    pub fn update_with_sp_playlist(&mut self, playlist: &spotify::Playlist) -> &mut Playlist {
        self.provider       = Provider::Spotify;
        self.identifier     = playlist.id.to_string();
        self.owner_id       = Some(playlist.owner.id.to_string());
        self.owner_name     = playlist.owner.display_name.clone();
        self.url            = playlist.uri.clone();
        self.title          = playlist.name.clone();
        self.description    = None;
        self.state          = State::Alive;
        self.published_at   = UTC::now().naive_utc();
        if playlist.images.len() > 0 {
            self.artwork_url   = Some(playlist.images[0].url.clone());
            self.thumbnail_url = Some(playlist.images[0].url.clone());
        }
        if playlist.images.len() > 1 {
            self.thumbnail_url = Some(playlist.images[1].url.clone());
        }
        self
    }

    pub fn update_with_sc_playlist(&mut self, playlist: &soundcloud::Playlist) -> &mut Playlist {
        self.provider      = Provider::SoundCloud;
        self.identifier    = playlist.id.to_string();
        self.owner_id      = Some(playlist.user.id.to_string());
        self.owner_name    = Some(playlist.user.username.clone());
        self.url           = playlist.permalink_url.to_string();
        self.title         = playlist.title.to_string();
        self.description   = None;
        self.thumbnail_url = playlist.artwork_url.clone();
        self.artwork_url   = playlist.artwork_url.clone();
        self.state         = State::Alive;
        match DateTime::parse_from_str(&playlist.created_at, "%Y/%m/%d %H:%M:%S %z") {
            Ok(published_at) => self.published_at = published_at.naive_utc(),
            Err(_)           => (),
        }
        self
    }

    pub fn update_with_am_playlist(&mut self, playlist: &apple_music::Playlist) -> &mut Playlist {
        self.provider      = Provider::AppleMusic;
        self.identifier    = playlist.id.to_string();
        self.owner_id      = Some(playlist.curator.to_string());
        self.owner_name    = Some(playlist.curator.to_string());
        self.url           = playlist.music_url.to_string();
        self.title         = playlist.title.to_string();
        self.description   = Some(playlist.description.to_string());
        self.thumbnail_url = Some(playlist.artwork_url.to_string());
        self.artwork_url   = Some(playlist.artwork_url.to_string());
        self.state         = State::Alive;
        self
    }

    pub fn disable(&mut self) -> &mut Playlist {
        self.state = State::Dead;
        self
    }

    pub fn delete(&self) -> Result<(), Error> {
        let conn = conn().unwrap();
        let stmt = conn.prepare("DELETE FROM playlists WHERE id=$1").unwrap();
        let result = stmt.query(&[&self.id]);
        match result {
            Ok(_)  => Ok(()),
            Err(_) => Err(Error::Unexpected)
        }
    }
}

#[cfg(test)]
mod test {
    use model::enclosure::Enclosure;
    use model::Model;
    use super::Playlist;
    use Provider;
    #[test]
    fn test_new() {
        let playlist = Playlist::new(Provider::YouTube,
                                     "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX".to_string());
        assert_eq!(playlist.provider, Provider::YouTube);
        assert_eq!(&playlist.identifier, "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX")
    }
    #[test]
    fn test_find_of_create() {
        let identifier = "PLy8LZ8FM-o0ViuGAF68RAaXkQ8V-3dbTX".to_string();
        let result     = Playlist::find_or_create(Provider::YouTube, identifier);
        assert!(result.is_ok());
    }
    #[test]
    fn test_delete() {
        let identifier = "test_delete".to_string();
        let playlist   = Playlist::find_or_create(Provider::YouTube, identifier).unwrap();
        let result     = playlist.delete();
        assert!(result.is_ok());
    }
    #[test]
    fn test_save() {
        let id = "test_save";
        let mut playlist = Playlist::find_or_create(Provider::YouTube, id.to_string()).unwrap();
        playlist.title = "title".to_string();
        let result = playlist.save();
        assert!(result.is_ok());
        let playlist = Playlist::find_or_create(Provider::YouTube, id.to_string()).unwrap();
        assert_eq!(&playlist.title, "title");
    }
}
<|endoftext|>


<commit_before>extern crate korome;
extern crate glium;

use korome::*;

use glium::Display;
use glium::texture::Texture2d;

macro_rules! print_type_info{
    ($($t:ty)*) => {
        $({
            use std::mem::{align_of, size_of};

            let (size, align) = (size_of::<$t>(), align_of::<$t>());
            println!("{}\t: {} <= {} * {}", stringify!($t), size, size/align, align);
        })*
    }
}

fn main(){
    print_type_info!(
        Drawer
        Texture
        Display
        Graphics
        FrameInfo
        Texture2d
        GameManager
        Vector2<f32>
        Vector2<f64>
        TextureError
        VirtualKeyCode
    );
}
<commit_msg>Remove size_info<commit_after><|endoftext|>


<commit_before>pub mod byteio;

use extbyteorder::ByteOrder;

use std::io::Result;

use super::{ReadAt, WriteAt};

/// Extends `ReadAt` with methods for reading numbers at offsets.
///
/// For most of these methods, you need to explicitly add a `ByteOrder` type parameter. See
/// [`byteorder::ReadBytesExt`][byteorder].
///
/// # Examples
///
/// Read an integer from the middle of a byte array:
///
/// ```rust
/// # extern crate positioned_io;
/// # extern crate byteorder;
/// # use std::io;
/// # use byteorder::BigEndian;
/// use positioned_io::ReadBytesAtExt;
///
/// # fn foo() -> io::Result<()> {
/// let buf = [0, 5, 254, 212, 0, 3];
/// let n = buf.as_ref().read_i16_at::<BigEndian>(2)?;
/// assert_eq!(n, -300);
/// # Ok(())
/// # }
/// # fn main() { foo().unwrap() }
/// ```
///
/// [byteorder]: http://burntsushi.net/rustdoc/byteorder/trait.ReadBytesExt.html
pub trait ReadBytesAtExt: ReadAt {
    /// Reads an unsigned 8-bit integer at an offset.
    fn read_u8_at(&self, pos: u64) -> Result<u8> {
        let mut buf = [0; 1];
        self.read_exact_at(pos, &mut buf)?;
        Ok(buf[0])
    }
    /// Reads a signed 8-bit integer at an offset.
    fn read_i8_at(&self, pos: u64) -> Result<i8> {
        let mut buf = [0; 1];
        self.read_exact_at(pos, &mut buf)?;
        Ok(buf[0] as i8)
    }
    /// Reads an unsigned 16-bit integer at an offset.
    fn read_u16_at<T: ByteOrder>(&self, pos: u64) -> Result<u16> {
        let mut buf = [0; 2];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u16(&buf))
    }
    /// Reads a signed 16-bit integer at an offset.
    fn read_i16_at<T: ByteOrder>(&self, pos: u64) -> Result<i16> {
        let mut buf = [0; 2];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i16(&buf))
    }
    /// Reads an unsigned 32-bit integer at an offset.
    fn read_u32_at<T: ByteOrder>(&self, pos: u64) -> Result<u32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u32(&buf))
    }
    /// Reads a signed 32-bit integer at an offset.
    fn read_i32_at<T: ByteOrder>(&self, pos: u64) -> Result<i32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i32(&buf))
    }
    /// Reads an unsigned 64-bit integer at an offset.
    fn read_u64_at<T: ByteOrder>(&self, pos: u64) -> Result<u64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u64(&buf))
    }
    /// Reads a signed 64-bit integer at an offset.
    fn read_i64_at<T: ByteOrder>(&self, pos: u64) -> Result<i64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i64(&buf))
    }
    /// Reads an unsigned `nbytes`-bit integer at an offset.
    fn read_uint_at<T: ByteOrder>(&self, pos: u64, nbytes: usize) -> Result<u64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf[..nbytes])?;
        Ok(T::read_uint(&buf[..nbytes], nbytes))
    }
    /// Reads a signed `nbytes`-bit integer at an offset.
    fn read_int_at<T: ByteOrder>(&self, pos: u64, nbytes: usize) -> Result<i64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf[..nbytes])?;
        Ok(T::read_int(&buf[..nbytes], nbytes))
    }
    /// Reads a single-precision floating point number at an offset.
    fn read_f32_at<T: ByteOrder>(&self, pos: u64) -> Result<f32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_f32(&buf))
    }
    /// Reads a double-precision floating point number at an offset.
    fn read_f64_at<T: ByteOrder>(&self, pos: u64) -> Result<f64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_f64(&buf))
    }
}

/// Extends `WriteAt` with methods for writing numbers at offsets.
///
/// For most of these methods, you need to explicitly add a `ByteOrder` type parameter. See
/// [`byteorder::WriteBytesExt`][byteorder].
///
/// # Examples
///
/// Write an integer to the middle of a byte array:
///
/// ```rust
/// # extern crate positioned_io;
/// # extern crate byteorder;
/// # use std::io;
/// # use byteorder::BigEndian;
/// use positioned_io::WriteBytesAtExt;
///
/// # fn foo() -> io::Result<()> {
/// let mut buf = [0; 6];
/// buf.as_mut().write_u16_at::<BigEndian>(2, 300)?;
/// assert_eq!(buf, [0, 0, 1, 44, 0, 0]);
/// # Ok(())
/// # }
/// # fn main() { foo().unwrap() }
/// ```
///
/// [byteorder]: http://burntsushi.net/rustdoc/byteorder/trait.WriteBytesExt.html
pub trait WriteBytesAtExt: WriteAt {
    /// Writes an unsigned 8-bit integer to an offset.
    fn write_u8_at(&mut self, pos: u64, n: u8) -> Result<()> {
        self.write_all_at(pos, &[n])
    }
    /// Writes a signed 8-bit integer to an offset.
    fn write_i8_at(&mut self, pos: u64, n: i8) -> Result<()> {
        self.write_all_at(pos, &[n as u8])
    }
    /// Writes an unsigned 16-bit integer to an offset.
    fn write_u16_at<T: ByteOrder>(&mut self, pos: u64, n: u16) -> Result<()> {
        let mut buf = [0; 2];
        T::write_u16(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 16-bit integer to an offset.
    fn write_i16_at<T: ByteOrder>(&mut self, pos: u64, n: i16) -> Result<()> {
        let mut buf = [0; 2];
        T::write_i16(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned 32-bit integer to an offset.
    fn write_u32_at<T: ByteOrder>(&mut self, pos: u64, n: u32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_u32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 32-bit integer to an offset.
    fn write_i32_at<T: ByteOrder>(&mut self, pos: u64, n: i32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_i32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned 64-bit integer to an offset.
    fn write_u64_at<T: ByteOrder>(&mut self, pos: u64, n: u64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_u64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 64-bit integer to an offset.
    fn write_i64_at<T: ByteOrder>(&mut self, pos: u64, n: i64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_i64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned `nbytes`-bit integer to an offset.
    fn write_uint_at<T: ByteOrder>(&mut self, pos: u64, n: u64, nbytes: usize) -> Result<()> {
        let mut buf = [0; 8];
        T::write_uint(&mut buf, n, nbytes);
        self.write_all_at(pos, &buf[..nbytes])
    }
    /// Writes a signed `nbytes`-bit integer to an offset.
    fn write_int_at<T: ByteOrder>(&mut self, pos: u64, n: i64, nbytes: usize) -> Result<()> {
        let mut buf = [0; 8];
        T::write_int(&mut buf, n, nbytes);
        self.write_all_at(pos, &buf[..nbytes])
    }
    /// Writes a single-precision floating point number to an offset.
    fn write_f32_at<T: ByteOrder>(&mut self, pos: u64, n: f32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_f32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a double-precision floating point number to an offset.
    fn write_f64_at<T: ByteOrder>(&mut self, pos: u64, n: f64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_f64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
}

// Implement for everything that does positioned IO.
impl<R: ReadAt> ReadBytesAtExt for R {}
impl<W: WriteAt> WriteBytesAtExt for W {}
<commit_msg>improve BytesAtExt docs<commit_after>pub mod byteio;

use extbyteorder::ByteOrder;

use std::io::Result;

use super::{ReadAt, WriteAt};

/// Extends `ReadAt` with methods for reading numbers at offsets.
///
/// For most of these methods, you need to explicitly add a `ByteOrder`
/// type parameter. Similar to [`byteorder::ReadBytesExt`][byteorder].
///
/// # Examples
///
/// Read an integer from the middle of a byte array:
///
/// ```rust
/// # extern crate positioned_io;
/// # extern crate byteorder;
/// # use std::io;
/// use byteorder::BigEndian;
/// use positioned_io::ReadBytesAtExt;
///
/// # fn try_main() -> io::Result<()> {
/// let buf = [0, 5, 254, 212, 0, 3];
/// let n = buf.as_ref().read_i16_at::<BigEndian>(2)?;
/// assert_eq!(n, -300);
/// # Ok(())
/// # }
/// # fn main() { try_main().unwrap() }
/// ```
///
/// [byteorder]: https://docs.rs/byteorder/1.2/byteorder/trait.ReadBytesExt.html
pub trait ReadBytesAtExt: ReadAt {
    /// Reads an unsigned 8-bit integer at an offset.
    fn read_u8_at(&self, pos: u64) -> Result<u8> {
        let mut buf = [0; 1];
        self.read_exact_at(pos, &mut buf)?;
        Ok(buf[0])
    }
    /// Reads a signed 8-bit integer at an offset.
    fn read_i8_at(&self, pos: u64) -> Result<i8> {
        let mut buf = [0; 1];
        self.read_exact_at(pos, &mut buf)?;
        Ok(buf[0] as i8)
    }
    /// Reads an unsigned 16-bit integer at an offset.
    fn read_u16_at<T: ByteOrder>(&self, pos: u64) -> Result<u16> {
        let mut buf = [0; 2];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u16(&buf))
    }
    /// Reads a signed 16-bit integer at an offset.
    fn read_i16_at<T: ByteOrder>(&self, pos: u64) -> Result<i16> {
        let mut buf = [0; 2];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i16(&buf))
    }
    /// Reads an unsigned 32-bit integer at an offset.
    fn read_u32_at<T: ByteOrder>(&self, pos: u64) -> Result<u32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u32(&buf))
    }
    /// Reads a signed 32-bit integer at an offset.
    fn read_i32_at<T: ByteOrder>(&self, pos: u64) -> Result<i32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i32(&buf))
    }
    /// Reads an unsigned 64-bit integer at an offset.
    fn read_u64_at<T: ByteOrder>(&self, pos: u64) -> Result<u64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_u64(&buf))
    }
    /// Reads a signed 64-bit integer at an offset.
    fn read_i64_at<T: ByteOrder>(&self, pos: u64) -> Result<i64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_i64(&buf))
    }
    /// Reads an unsigned `nbytes`-bit integer at an offset.
    fn read_uint_at<T: ByteOrder>(&self, pos: u64, nbytes: usize) -> Result<u64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf[..nbytes])?;
        Ok(T::read_uint(&buf[..nbytes], nbytes))
    }
    /// Reads a signed `nbytes`-bit integer at an offset.
    fn read_int_at<T: ByteOrder>(&self, pos: u64, nbytes: usize) -> Result<i64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf[..nbytes])?;
        Ok(T::read_int(&buf[..nbytes], nbytes))
    }
    /// Reads a single-precision floating point number at an offset.
    fn read_f32_at<T: ByteOrder>(&self, pos: u64) -> Result<f32> {
        let mut buf = [0; 4];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_f32(&buf))
    }
    /// Reads a double-precision floating point number at an offset.
    fn read_f64_at<T: ByteOrder>(&self, pos: u64) -> Result<f64> {
        let mut buf = [0; 8];
        self.read_exact_at(pos, &mut buf)?;
        Ok(T::read_f64(&buf))
    }
}

/// Extends `WriteAt` with methods for writing numbers at offsets.
///
/// For most of these methods, you need to explicitly add a `ByteOrder` type
/// parameter. Similar to [`byteorder::WriteBytesExt`][byteorder].
///
/// # Examples
///
/// Write an integer to the middle of a byte array:
///
/// ```rust
/// # extern crate positioned_io;
/// # extern crate byteorder;
/// # use std::io;
/// use byteorder::BigEndian;
/// use positioned_io::WriteBytesAtExt;
///
/// # fn try_main() -> io::Result<()> {
/// let mut buf = [0; 6];
/// buf.as_mut().write_u16_at::<BigEndian>(2, 300)?;
/// assert_eq!(buf, [0, 0, 1, 44, 0, 0]);
/// # Ok(())
/// # }
/// # fn main() { try_main().unwrap() }
/// ```
///
/// [byteorder]: https://docs.rs/byteorder/1.2/byteorder/trait.WriteBytesExt.html
pub trait WriteBytesAtExt: WriteAt {
    /// Writes an unsigned 8-bit integer to an offset.
    fn write_u8_at(&mut self, pos: u64, n: u8) -> Result<()> {
        self.write_all_at(pos, &[n])
    }
    /// Writes a signed 8-bit integer to an offset.
    fn write_i8_at(&mut self, pos: u64, n: i8) -> Result<()> {
        self.write_all_at(pos, &[n as u8])
    }
    /// Writes an unsigned 16-bit integer to an offset.
    fn write_u16_at<T: ByteOrder>(&mut self, pos: u64, n: u16) -> Result<()> {
        let mut buf = [0; 2];
        T::write_u16(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 16-bit integer to an offset.
    fn write_i16_at<T: ByteOrder>(&mut self, pos: u64, n: i16) -> Result<()> {
        let mut buf = [0; 2];
        T::write_i16(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned 32-bit integer to an offset.
    fn write_u32_at<T: ByteOrder>(&mut self, pos: u64, n: u32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_u32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 32-bit integer to an offset.
    fn write_i32_at<T: ByteOrder>(&mut self, pos: u64, n: i32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_i32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned 64-bit integer to an offset.
    fn write_u64_at<T: ByteOrder>(&mut self, pos: u64, n: u64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_u64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a signed 64-bit integer to an offset.
    fn write_i64_at<T: ByteOrder>(&mut self, pos: u64, n: i64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_i64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes an unsigned `nbytes`-bit integer to an offset.
    fn write_uint_at<T: ByteOrder>(&mut self, pos: u64, n: u64, nbytes: usize) -> Result<()> {
        let mut buf = [0; 8];
        T::write_uint(&mut buf, n, nbytes);
        self.write_all_at(pos, &buf[..nbytes])
    }
    /// Writes a signed `nbytes`-bit integer to an offset.
    fn write_int_at<T: ByteOrder>(&mut self, pos: u64, n: i64, nbytes: usize) -> Result<()> {
        let mut buf = [0; 8];
        T::write_int(&mut buf, n, nbytes);
        self.write_all_at(pos, &buf[..nbytes])
    }
    /// Writes a single-precision floating point number to an offset.
    fn write_f32_at<T: ByteOrder>(&mut self, pos: u64, n: f32) -> Result<()> {
        let mut buf = [0; 4];
        T::write_f32(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
    /// Writes a double-precision floating point number to an offset.
    fn write_f64_at<T: ByteOrder>(&mut self, pos: u64, n: f64) -> Result<()> {
        let mut buf = [0; 8];
        T::write_f64(&mut buf, n);
        self.write_all_at(pos, &buf)
    }
}

// Implement for everything that does positioned I/O.
impl<R: ReadAt> ReadBytesAtExt for R {}
impl<W: WriteAt> WriteBytesAtExt for W {}
<|endoftext|>


<commit_before>pub use self::cargo_clean::{clean, CleanOptions};
pub use self::cargo_compile::{compile, compile_with_exec, compile_ws, CompileOptions};
pub use self::cargo_compile::{CompileFilter, CompileMode, MessageFormat, Packages};
pub use self::cargo_read_manifest::{read_package, read_packages};
pub use self::cargo_rustc::{compile_targets, Compilation, Kind, Unit};
pub use self::cargo_rustc::{Context, is_bad_artifact_name};
pub use self::cargo_rustc::{BuildOutput, BuildConfig, TargetConfig};
pub use self::cargo_rustc::{Executor, DefaultExecutor};
pub use self::cargo_run::run;
pub use self::cargo_install::{install, install_list, uninstall};
pub use self::cargo_new::{new, init, NewOptions, VersionControl};
pub use self::cargo_doc::{doc, DocOptions};
pub use self::cargo_generate_lockfile::{generate_lockfile};
pub use self::cargo_generate_lockfile::{update_lockfile};
pub use self::cargo_generate_lockfile::UpdateOptions;
pub use self::lockfile::{load_pkg_lockfile, write_pkg_lockfile};
pub use self::cargo_test::{run_tests, run_benches, TestOptions};
pub use self::cargo_package::{package, PackageOpts};
pub use self::registry::{publish, registry_configuration, RegistryConfig};
pub use self::registry::{registry_login, search, http_proxy_exists, http_handle};
pub use self::registry::{modify_owners, yank, OwnersOptions, PublishOpts};
pub use self::cargo_fetch::fetch;
pub use self::cargo_pkgid::pkgid;
pub use self::resolve::{resolve_ws, resolve_ws_precisely, resolve_with_previous};
pub use self::cargo_output_metadata::{output_metadata, OutputMetadataOptions, ExportInfo};

mod cargo_clean;
mod cargo_compile;
mod cargo_doc;
mod cargo_fetch;
mod cargo_generate_lockfile;
mod cargo_install;
mod cargo_new;
mod cargo_output_metadata;
mod cargo_package;
mod cargo_pkgid;
mod cargo_read_manifest;
mod cargo_run;
mod cargo_rustc;
mod cargo_test;
mod lockfile;
mod registry;
mod resolve;
<commit_msg>Expose ops::cargo_compile::FilterRule<commit_after>pub use self::cargo_clean::{clean, CleanOptions};
pub use self::cargo_compile::{compile, compile_with_exec, compile_ws, CompileOptions};
pub use self::cargo_compile::{CompileFilter, CompileMode, FilterRule, MessageFormat, Packages};
pub use self::cargo_read_manifest::{read_package, read_packages};
pub use self::cargo_rustc::{compile_targets, Compilation, Kind, Unit};
pub use self::cargo_rustc::{Context, is_bad_artifact_name};
pub use self::cargo_rustc::{BuildOutput, BuildConfig, TargetConfig};
pub use self::cargo_rustc::{Executor, DefaultExecutor};
pub use self::cargo_run::run;
pub use self::cargo_install::{install, install_list, uninstall};
pub use self::cargo_new::{new, init, NewOptions, VersionControl};
pub use self::cargo_doc::{doc, DocOptions};
pub use self::cargo_generate_lockfile::{generate_lockfile};
pub use self::cargo_generate_lockfile::{update_lockfile};
pub use self::cargo_generate_lockfile::UpdateOptions;
pub use self::lockfile::{load_pkg_lockfile, write_pkg_lockfile};
pub use self::cargo_test::{run_tests, run_benches, TestOptions};
pub use self::cargo_package::{package, PackageOpts};
pub use self::registry::{publish, registry_configuration, RegistryConfig};
pub use self::registry::{registry_login, search, http_proxy_exists, http_handle};
pub use self::registry::{modify_owners, yank, OwnersOptions, PublishOpts};
pub use self::cargo_fetch::fetch;
pub use self::cargo_pkgid::pkgid;
pub use self::resolve::{resolve_ws, resolve_ws_precisely, resolve_with_previous};
pub use self::cargo_output_metadata::{output_metadata, OutputMetadataOptions, ExportInfo};

mod cargo_clean;
mod cargo_compile;
mod cargo_doc;
mod cargo_fetch;
mod cargo_generate_lockfile;
mod cargo_install;
mod cargo_new;
mod cargo_output_metadata;
mod cargo_package;
mod cargo_pkgid;
mod cargo_read_manifest;
mod cargo_run;
mod cargo_rustc;
mod cargo_test;
mod lockfile;
mod registry;
mod resolve;
<|endoftext|>